MongoDB aggregate project return an array of _id [duplicate]

蹲街弑〆低调 提交于 2019-12-11 07:06:05

问题


As we know if we want to get an array of _id we can do:

db.collections.distinct("_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}
    }
     )

I get

{
"_id" : "1",
"_id" : "2"
}

what i want is just like we do distinct

{[1,2]}

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}}
     )

but i still get

{
all : ["1","2"]
}

or I can do .map(function(el) { return el._id }) after getting

{
    "_id" : "1",
    "_id" : "2"
    }

, but the map is client side transformation which I think it will affect the performance.


回答1:


Edit: Quoting from: How to return array of string with mongodb aggregation

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}
    }
])


来源:https://stackoverflow.com/questions/46599079/mongodb-aggregate-project-return-an-array-of-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!