RSKMR RSKMR - 2 months ago 19
Node.js Question

Mongo + check multiple fields existing

I am working mongo with nodejs.

I have array list:

var checkFields = ["field1","field2","field3"];


I try to get the count of records having the array list fields and user field is equal to admin.

Sample data:

[
{
"checkFields": {
"field1": "00124b3a5c31",
"user": "admin"
}
},
{
"checkFields": {
"field2": "00124b3a5c31",
"user": "admin"
}
},
{
"checkFields": {
"field1": "00124b3a5c31",
"user": "regular"
}
}
]


Query:

db.collection_name.find(
{"checkFields.user" : "admin"}
{ "checkFields.field1": { $exists: true} }
)


Expected Result:

Result is to get rows of count of matching the field in array
list(checkFields)
.

Answer

Building up an $or array for the list of field existence checks is the right approach, but assuming you're on a current node.js build you can simplify the query creation to:

var checkFieldsLists = checkFields.map(field => ({
    ['checkFields.' + field]: {$exists: true}
}));
var query = {
    $or: checkFieldsLists,
    'checkFields.user': 'admin'
}

This removes the superfluous $or for the "user is admin" check which lets you also remove the outer $and, so that the generated query is:

{ '$or':
   [ { 'checkFields.field1': { '$exists': true } },
     { 'checkFields.field2': { '$exists': true } },
     { 'checkFields.field3': { '$exists': true } } ],
  'checkFields.user': 'admin' }