Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB aggregate project return an array of _id [duplicate]

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.

like image 741
Chi Dov Avatar asked Jan 29 '23 11:01

Chi Dov


1 Answers

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}
    }
])
like image 72
Dushyant Bangal Avatar answered Feb 01 '23 16:02

Dushyant Bangal