MongoDB聚合项目返回_id数组 [英] MongoDB aggregate project return an array of _id
本文介绍了MongoDB聚合项目返回_id数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们知道是否要获取_id数组,我们可以这样做:
As we know if we want to get an array of _id we can do:
db.collections.distinct("_id");
我的问题是,如果我需要对聚合进行复杂的逻辑运算,该如何获取_id数组. 例如:
My question is how can I get an array of _id if I need to do a complicate logic with aggregate. Ex:
db.getCollection('users').aggregate({
$match : {
is_register_completed : { $ne : true}
}
}
//other operator like $lookup, $group
,
{
$project : {_id:1}
}
)
我知道
{
"_id" : "1",
"_id" : "2"
}
我想要的就像我们做的独特
what i want is just like we do distinct
{[1,2]}
已更新: 这就是我尝试使用$ group
Updated: this is what i try to do with $group
db.getCollection('users').aggregate({
$match : {
is_register_completed : { $ne : true}
}
},
{
$group: {
_id:null, all:{$addToSet: "$_id"}
}
}, {$project: {_id:0,all:1}}
)
但我仍然得到
{
all : ["1","2"]
}
或者我可以在获得
{
"_id" : "1",
"_id" : "2"
}
,但是地图是客户端转换,我认为这会影响性能.
, but the map is client side transformation which I think it will affect the performance.
推荐答案
.aggregate()方法始终返回对象,无论您做什么 并不能改变.
The .aggregate() method always returns Objects no matter what you do and that cannot change.
原始答案:
尝试使用聚合框架:
Original Answer:
Try the aggregation framework:
db.myCol.aggregate([
{
$group:{_id:null, array:{$push:"$_id"}}
},
{
$project:{array:true,_id:false}
}
])
这篇关于MongoDB聚合项目返回_id数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文