Orion
Orion

Reputation: 174

Aggregate and search nested documents

Lets say I have a collection of documents that looks something like this:

{ "_id": "123", "arr": [ { "num": 1, "_id": "231" } ] },
{ "_id": "234", "arr": [ { "num": 3, "_id": "321" }, { "num": 1, "_id": "294" } ] },
{ "_id": "345", "arr": [ { "num": 3, "_id": "653" }, { "num": 1, "_id": "732" } ] },
{ "_id": "456", "arr": [ { "num": 2, "_id": "123" } ] },

How could I write a query to search for all "arr" objects where "num" is 1 and get something like:

{ "num": 1, "_id": "231" },
{ "num": 1, "_id": "294" },
{ "num": 1, "_id": "732" }

I have tried to use $unwind but so far been unsuccessful.

Upvotes: 0

Views: 30

Answers (1)

Haniel Baez
Haniel Baez

Reputation: 1690

Try this:

  1. Filters the documents to pass only the documents that match arr.num === 1
  2. Deconstructs the arr field with $unwind
  3. Filters the documents arr.num === 1
  4. Replaces the input document with the arr document

.

db.collection.aggregate({
      $match: {
        "arr.num": 1
      }
    },
    {
      $unwind: "$arr"
    },
    {
      $match: {
        "arr.num": 1
      }
    },
    {
      $replaceRoot: {
        newRoot: "$arr"
      }
    });

Output:

[
  {
    "_id": "231",
    "num": 1
  },
  {
    "_id": "294",
    "num": 1
  },
  {
    "_id": "732",
    "num": 1
  }
]

Upvotes: 1

Related Questions