Related to: mongodb/meteor collection check if subdocument field exists when field is a variable
I'm trying to query a Meteor collection by building an object with some variable field names. This works when the object has one field, for example
var query = {};
query['myField.'+myVariable] = {$exists: true};
Collection.find(query); //works fine
But I need to query with multiple selectors. For example, I need to check that a field name with a variable exists, and also check if some other field = true, and if some other field = a variable. So I'm trying to find a general way to build query objects. I have tried the following:
var query = {};
query['myField.'+myVariable] = {$exists: true};
query[newField] = false;
Collection.find(query);
This doesn't work. I'm not sure if that's because the 'newField' is not of type Object or something.
I've tried also using the $and selector to see if that works but I don't think the syntax I'm using is exactly correct...
var query = {};
var object = {};
object['myField'.+myVariable] = {$exists: true};
query['$and'] = [object, {newField: false}];
Collection.find(query);
This also doesn't work. I was trying to build with the mongo $and selector which works by using an array.
How do I syntactically build a Meteor collection query with javascript object notation and object literals? I feel like either one of these should work.
To be specific, I'm looking for the following (semi pseudocode since getting a subdocument/subobject with dot notation doesn't work with a mongo query)
Collection.find({correlated: false, readBy.(Meteor.userId()): {$exists: true} ...)
I also thought this should work:
var query = {};
query['myField.'+myVariable] = {$exists: true};
Collection.find(query, {otherField: false})
//OR
var query2 = {};
query['priority'] = false;
Collection.find(query, query2)
But neither of them do.
EDIT: example doc. I want to find the document such that the current user ID is NOT a readBy field AND has correlated: false
{
"_id" : ObjectId("55b6868906ce5d7b1ac6af10"),
"title" : "test",
"correlated" : "false",
"readBy" : {
"DXqLhesDEJq4ye8Dy" : ISODate("2015-07-27T18:29:43.592Z")
}
}
readBywhich is an object. The fields of this object are the userIds and the value of these fields is the timestamp. I then have another field separate from that calledcorrelatedwhich is eithertrueorfalse. I want to find every document that has theuserIdfield in thereadBysubdocument AND hascorrelated = false.