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.
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}
}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With