Find results with a specific number of fields in my MongoDB subdirectory

I would like to request a subdocument in which the results should have all fields specified and others . Is it possible? And if so, how?

For instance:

I need a query like this:

db.users.find({ 
    "pref.no_popup": true, 
    "pref.font_large": false, 
    "pref": { "$size", 2 }});

To fit this:

{
  "user": "Ed",
  "pref": {
    "no_popup": true,
    "font_large": false
  }
}

But not this:

{
  "user": "James",
  "pref": {
    "no_popup": true,
    "font_large": false,
    "font_red": true
  }
}

I understand that the $ size operator is for arrays, so how can I do something similar for subdocuments?

Note that I tried not to use dot notation to request the exact presence of the field, but then I had problems with ordering.

+3
source share
4 answers

" ". , .

, :

db.users.find({ 
    "pref" : {
        "no_popup" : true,
        "font_large" : false
    } });
+1

$exist operator?

db.users.find({ 
    "pref.font_red" : {"$exists":false}
});
+1

If you have many properties that you don’t want to match, and only two, which is usually the case, you can try something like this to solve the order problem (like updating to Andrey’s answer):

db.users.find({ $or: [
"pref" : {
    "no_popup" : true,
    "font_large" : false
},
"pref" : {       
    "font_large" : false,
    "no_popup" : true
} ] });
+1
source

I think you have to use mapReduce ...

Not perfect, but should solve the problem.

mapper=function(){ for (key in this.pref){
  emit(this._id, {'count':1}); \\assume your user id is called _id
  }
}
reducer=function(k,v){ 
  counter=0; 
  for (i=0;i<v.length;i++){
    counter+=v[i].count;
  }
  return {'count':counter}
 }

This should give you a collection with people ids and the number of prefs that have been set

0
source

All Articles