Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongodb $ operator for nested documents

there is a wfs collection as follows:

{
_id:'1',
transitions:
  [
    {
     _id:'11',
     checkLists:
       [
        {
         _id:'111',
         name:'One',
        },
        {
         _id:'112',
         name:'Two',
        }
       ]
     }
  ]
}

I would like to get the sub sub document of _id:’111′
I have tried the following code but not working as expected, it returns all of 2nd level nested documents not the proper object

db.wfs.findOne(
    { 'transitions.checkLists._id':  ObjectId('111') },
    { 'transitions.checkLists._id': 1 },
  );

result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
transitions: [
  {
    "checkLists": [
      {
        "name": "One",
        "_id": "111"
      },
      {
        "name": "Two",
        "_id": "112"
      }
    ]
  }
]
}

Expected result:

[
  {
    "checkLists": [
      {
        "name": "One",
        "_id": "111"
      }
    ]
  }
]

appreciated any hint or solution

>Solution :

You can use:

db.collection.aggregate([
  {
    $match: {"transitions.checkLists._id": "111"}
  },
  {
    $project: {
      transitions: {
        $reduce: {
          "input": "$transitions",
          initialValue: [],
          in: {$concatArrays: ["$$value", "$$this.checkLists" ]}
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      checkLists: {
        $filter: {
          input: "$transitions",
          as: "item",
          cond: {$eq: ["$$item._id",  "111" ]}
        }
      }
    }
  }
])

As you can see on this playground example.

The $reduce is used to "flatten" your list, and the $filter is used to keep only the part you want.

This is based on this solution by @rickhg12hs to a basically similar, but little more complex, problem. The solution here is just a simple version of it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading