Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb: return an array of document ids

Is it possible to query mongodb to return array of matching document id values, without the related keys?

Please consider following 'parent' data structur:

{
  "_id": ObjectId("52448e4697fb2b775cb5c3a7"),
  "name": "Peter",
  "children": [
    {
      "name": "joe"
    }
  ]
},
{
  "_id": ObjectId("52448e4697fb2b775cb5c3b6"),
  "name": "Marry",
  "children": [
    {
      "name": "joe"
    }
  ]
}

I would to query for an array of parent _ids whose children have the name "joe"

For provided sample data, I would like the following output returned from mongo:

[ObjectId("52448e4697fb2b775cb5c3a7"), ObjectId("52448e4697fb2b775cb5c3b6")]

I know that I can query for an output like this, which also contains the keys

[{"_id": ObjectId("52448e4697fb2b775cb5c3a7")}, {"_id": ObjectId("52448e4697fb2b775cb5c3b6")}]

However I need to push above array to another document with an update operation like this:

db.statistic.update({"date": today}, {$push: {"children": [ObjectId("52448e4697fb2b775cb5c3a7"), ObjectId("52448e4697fb2b775cb5c3b6")]}}, true, false)

I would like to avoid sorting out the document structure, in case it is possible to just return an array containing the appropriate values using mongo

like image 464
st-h Avatar asked Sep 27 '13 19:09

st-h


1 Answers

It should be possible by

db.coll.distinct("_id", {"children.name": "joe"})
like image 51
viktortnk Avatar answered Nov 23 '22 08:11

viktortnk