Linked to: mongodb/meteor collection check if subdocument field exists when field is a variable
I am attempting to perform a query on a Meteor collection by constructing an object with dynamic field names. This method works when the object has a single field, as shown below
var query = {};
query['myField.'+myVariable] = {$exists: true};
Collection.find(query); //works fine
However, I need to query with multiple criteria. For instance, I need to verify the presence of a field with a variable name, along with checking if another field equals true, and if yet another field equals a variable. I am trying to create a general approach to building query objects. I have attempted the following:
var query = {};
query['myField.'+myVariable] = {$exists: true};
query[newField] = false;
Collection.find(query);
This approach does not yield the desired results. I suspect this may be due to 'newField' not being an Object type or some other reason.
I also tried using the $and selector, but my syntax might not be correct...
var query = {};
var object = {};
object['myField'.+myVariable] = {$exists: true};
query['$and'] = [object, {newField: false}];
Collection.find(query);
Unfortunately, this approach also leads to issues. I was attempting to utilize the mongo $and selector, which requires an array.
How can I construct a Meteor collection query using JavaScript object notation and object literals? I believe one of these methods should work.
To elaborate, I am seeking something similar to the following (partly pseudocode due to the limitations of dot notation in a mongo query)
Collection.find({correlated: false, readBy.(Meteor.userId()): {$exists: true} ...)
I also thought the following should work:
var query = {};
query['myField.'+myVariable] = {$exists: true};
Collection.find(query, {otherField: false})
//OR
var query2 = {};
query['priority'] = false;
Collection.find(query, query2)
However, neither of these approaches yield the desired results.
EDIT: Example document - I wish to find a document where the current user ID is NOT listed in the readBy field AND correlated is set to false
{
"_id" : ObjectId("55b6868906ce5d7b1ac6af10"),
"title" : "test",
"correlated" : "false",
"readBy" : {
"DXqLhesDEJq4ye8Dy" : ISODate("2015-07-27T18:29:43.592Z")
}
}