Search code examples
mongodbcompass

Find objects in nested array, mongodb, compass


I'm using Mongodb database and Compass tool to visualize my data. My collection called 'ProbCancer' looks like that:

probCancers: [
        cases: [
                {
                   case: {
                   bi: Number,
                   age: Number,
                 },
                   level: Number,
                   _id: false,
                }
              ]
            ]

Since I have many objects in the cases array, it's hard to analyze them. I want to only find objects that have level = -1. Is there any way to do this query in compass? Giving the query parameter in db.probCancers.find(query); could be helpful for me as well.


Solution

  • I found how to do it in mongoDB shell from this link: Mongodb, search object in nested Array, but I don't know why it doesn't work in compass version 1.11.2.

    There is a solution by defining the query parameter like that: {cases: {$elemMatch: { level: -1}}}, and to prevent getting the full cases array we should specify the projection field. It's the same as the query field. But this solution returns the first object in the cases array that matches with level = -1.

    So, this is the result:

    db.probCancer.find({cases: {$elemMatch: { level: -1}}}, 
                       {cases: {$elemMatch: { level: -1}}}
                      );
    

    In mongoDB, to do queries in a nested array, the array must be flatted. Then the query would be done in the resulted flatted array. To do so, we need to use pipeline aggregation see the link.

    And this code will give us the wanted result:

    db.probCancer.aggregate([ { $unwind : "$cases" }, { $match : {"cases.level":-1}} ]);