我有以下收藏
{
"_id" : ObjectId("5acdb95d5ea63a27c1facf92"),
"venue" : ObjectId("5acdb95d5ea63a27c1facf8c"),
"author" : ObjectId("5ac8ba3582c2345af70d4658"),
}
{
"_id" : ObjectId("5acdb95d5ea63a27c1facf93"),
"venue" : ObjectId("5acdb95d5ea63a27c1facf8c"),
"author" : ObjectId("5ac8ba3582c2345af70d4658"),
}
{
"_id" : ObjectId("5acdb95d5ea63a27c1facf91"),
"venue" : ObjectId("5acdb95d5ea63a27c1facf8c"),
"author" : ObjectId("5ac8ba3582c2345af70d4658"),
}
如何在具有相同位置的数组中获取所有_id
我的输出应该是这样的
{array: ['5acdb95d5ea63a27c1facf91', '5acdb95d5ea63a27c1facf91', '5acdb95d5ea63a27c1facf93']}
答案 0 :(得分:3)
尝试此查询:
db.colelction.aggregate([
{$match:{"venue" : ObjectId("5acdb95d5ea63a27c1facf8c")}},
{$group:{_id:null, array:{$push:"$_id"}}},
{$project:{_id:0}}
])
输出是:
/* 1 */
{
"array" : [
ObjectId("5acdb95d5ea63a27c1facf92"),
ObjectId("5acdb95d5ea63a27c1facf93"),
ObjectId("5acdb95d5ea63a27c1facf91")
]
}
答案 1 :(得分:0)
db.collection.aggregate(
// Pipeline
[
// Stage 1
{
$group: {
_id:{venue:'$venue'},
_ids:{$addToSet:'$_id'}
}
},
// Stage 2
{
$project: {
_ids:1,
_id:0
}
}
]
);