3

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.

3 Answers3

7

Unfortunately $elemMatch projections are not supported in Compass. There is an open tracker for the issue. (I don't have enough reputation to comment on Bentaiba's answer.)

Edit1:
The issue above was closed (fixed) Sep 27 2019.

Igorski
  • 428
  • 9
  • 16
2

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}} ]);
0

How about trying:

db.ProbCancer.find( { "cases.level" : -1 } )

Or you can use $all you can find more infos in the official documentations of mongodb : Link to documentation

  • 1
    `db.ProbCancer.find( { "cases.level" : -1 } )` won't work only if I add the index of the array, for example `db.ProbCancer.find( { "cases.12.level" : -1 } )` gives me all documents were `cases[12].level = -1`. – Bentaiba Miled Basma Feb 22 '18 at 19:10