MongoDB聚合推送索引
Posted
技术标签:
【中文标题】MongoDB聚合推送索引【英文标题】:Mongodb aggregate push index 【发布时间】:2019-07-22 11:04:55 【问题描述】:我有以下文件:
_id: "1",
firstName: "john",
lastName: "Doe",
cars: [
"_id": "2",
"carName": "BMW",
"carModel": "330",
"carColor": "silver"
,
"_id": "4",
"carName": "BMW",
"carModel": "330",
"carColor": "pink"
,
"_id": "5",
"carName": "Lexus",
"carModel": "IS300",
"carColor": "white"
,
"_id": "6",
"carName": "LADA",
"carModel": "2106",
"carColor": "blue"
]
使用聚合查询,我从以下文档的 cars
数组返回特定对象:
db.collection.aggregate([
$match:
firstName: "john"
,
$unwind: "$cars"
,
$match:
"cars.carName":
"$in": [
"Lexus",
"LADA"
]
,
$group:
"_id": null,
cars:
$push: "$cars"
])
是否也可以获取推送到cars
数组的每个对象的索引?
例如:
[
"_id": null,
"cars": [
"_id": "5",
"carColor": "white",
"carModel": "IS300",
"carName": "Lexus",
"index": 2
,
"_id": "6",
"carColor": "blue",
"carModel": "2106",
"carName": "LADA",
"index": 4
]
]
可以测试聚合查询here
【问题讨论】:
【参考方案1】:您可以尝试以下聚合 (includeArrayIndex
)
db.collection.aggregate([
"$match": "firstName": "john" ,
"$unwind": "path": "$cars", "includeArrayIndex": "index", ,
"$match": "cars.carName": "$in": ["Lexus", "LADA"] ,
"$addFields": "cars.index": "$index" ,
"$group":
"_id": null,
"cars": "$push": "$cars"
])
Mongoplayground
【讨论】:
是否有其他方法可以在不使用$mergeObjects
的情况下实现这一目标?我有 3.2 版本的 mongoDb,它不支持该属性。
我*更新了我的答案
非常感谢。这个答案对我帮助很大!我被这个索引问题困了几个小时。以上是关于MongoDB聚合推送索引的主要内容,如果未能解决你的问题,请参考以下文章