答案 0 :(得分:2)
要将每个 _id
的数组放入您的对象中,您可以使用 $map
。
Map 类似于 JS 地图,请检查:
const array = [
{"id": 1,"other": ""},
{"id": 2,"other": ""},
{"id": 3,"other": ""},
{"id": 4,"other": ""},
{"id": 5,"other": ""}]
console.log(array.map(m => m.id))
您可以使用 mongo $map
将这种方法引入 $project
阶段,如下所示:
通过此聚合,您将创建一个名为 array
的字段,其中使用 $map
返回 array.id
,因此它会创建一个包含所需 ID 的数组。
db.collection.aggregate([
{
"$project": {
"_id": 0,
"array": {
"$map": {
"input": "$array",
"as": "a",
"in": "$$a.id"
}
}
}
}
])
示例here