Mongo在对象数组中按id查找位置

用户2829319

我有一系列文件

{
    _id: ObjectId("5e388da4df54cb8efb47e61b"),
    userId:'test_user'
    productId:'product_6_id'
    recommendations:{
    _id:123
     rankedList:[
        0:{id:ObjectId('product_5_id'),Name:'Product_5'},
        1:{id:ObjectId('product_6_id'),Name:'Product_6'},
        2:{id:ObjectId('product_3_id'),Name:'Product_3'}],
    Date:'2020-02-25T05:03:55.439+00:00'
    }
    
},
{
    _id: ObjectId("5e388da4df54cb8efb47e62b"),
    userId:'test_user1'
    productId:'product_3_id'
    recommendations:{
    _id:123
     rankedList:[
        0:{id:ObjectId('product_1_id'),Name:'Product_1'},
        1:{id:ObjectId('product_5_id'),Name:'Product_5'},
        2:{id:ObjectId('product_3_id'),Name:'Product_3'}],
    Date:'2020-02-25T05:03:55.439+00:00'
    }
    
}

并且我每次都需要找到productId对象数组中的位置rankedList因此,这里的答案是第一个文档的positionIndex=1第二个文档的positionIndex=2我很困惑$indexOfArray以及我应该如何在这里使用聚合。

米克尔

是的,你需要$indexOfArray棘手的部分是recommendations.rankedList对象数组,但是 MongoDB 允许您使用以下表达式:

$recommendations.rankedList.id

其计算结果为字符串列表,['product_5_id', 'product_6_id', 'product_3_id']在这种情况下,您的代码可以如下所示:

db.collection.aggregate([
    {
        $project: {
            index: {
                $indexOfArray: [ "$recommendations.rankedList.id", "$productId" ]
            }
        }
    }
])

蒙戈游乐场

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章