我有一系列文件
{
_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] 删除。
我来说两句