Jordi
Jordi

Reputation: 23237

MongoDb: Query over an array of nested documents

I've inserted this document into db.references collections:

{
   "idRef":"asdf-ggtt-001",
   "metadades":[
      {
         "departament":"JUST",
         "changed": ISODate("2016-02-10T10:50:42.389Z")
      },
      {
         "ambit":"AMB1"
      }
   ]
}

So, I'd like to get which documents have a metadades.changed informed, where metadades is an array of nested documents.

Any ideas?

Upvotes: 0

Views: 40

Answers (1)

mdewit
mdewit

Reputation: 2036

For the full document (parent with nested documents):

db.references.find({"metadades.changed": {$exists: 1}}).pretty()

This will basically produce all documents with at least one nested document with the changed field present.

If you only want the nested document that matched:

db.references.aggregate([
{
    $unwind: {
        path: "$metadades"
    }
},
{
    $match: {
        "metadades.changed": {$exists: 1}
    }
},
{
    $replaceRoot: {
        "newRoot": "$metadades"
    }
}
])

Upvotes: 1

Related Questions