首页 文章

使用javascript对象进行mongodb / meteor集合查询

提问于
浏览
2

相关:mongodb/meteor collection check if subdocument field exists when field is a variable

我正在尝试通过构建具有一些可变字段名称的对象来查询Meteor集合 . 例如,当对象具有一个字段时,这可以工作

var query = {};
query['myField.'+myVariable] = {$exists: true};
Collection.find(query); //works fine

但我需要使用多个选择器进行查询 . 例如,我需要检查带有变量的字段名称是否存在,还检查是否有其他field = true,以及是否有其他field =变量 . 所以我试图找到一种构建查询对象的通用方法 . 我尝试过以下方法:

var query = {};
query['myField.'+myVariable] = {$exists: true};
query[newField] = false;
Collection.find(query);

这不起作用 . 我不确定是不是因为'newField'不是Object类型的东西 .

我也试过使用$和选择器看看是否有效,但我不认为我使用的语法是完全正确的...

var query = {};
var object = {};
object['myField'.+myVariable] = {$exists: true};
query['$and'] = [object, {newField: false}];
Collection.find(query);

这也行不通 . 我试图用mongo $和选择器构建,它使用数组工作 .

如何使用javascript对象表示法和对象文字语法构建Meteor集合查询?我觉得其中任何一个都应该有效 .

具体来说,我正在寻找以下(半伪代码,因为获得带有点符号的子文档/子对象不适用于mongo查询)

Collection.find({correlated: false, readBy.(Meteor.userId()): {$exists: true} ...)

我还认为这应该有效:

var query = {};
query['myField.'+myVariable] = {$exists: true};
Collection.find(query, {otherField: false}) 
//OR 
var query2 = {};
query['priority'] = false;
Collection.find(query, query2)

但他们都不这样做 .

编辑:示例文档 . 我想找到这样的文档,使得当前用户ID不是readBy字段并且具有相关性:false

{
    "_id" : ObjectId("55b6868906ce5d7b1ac6af10"),
    "title" : "test",
    "correlated" : "false",
    "readBy" : {
        "DXqLhesDEJq4ye8Dy" : ISODate("2015-07-27T18:29:43.592Z")
    }
}

1 回答

  • 1

    find 只有一个选择器参数 . 所以这:

    Collection.find(query, {otherField: false})
    

    是不正确的 . query 必须包含有关 otherField 的信息 . 仔细看看这个示例代码:

    // 'readBy.abc123'
    var key = 'readBy.' + Meteor.userId();
    
    // build the selector by parts
    var selector = {correlated: false};
    selector[key] = {$exists: false};
    
    // selector should now be something like:
    // {correlated: false, 'readBy.abc123': {$exists: false}}
    // note that these are ANDed together so all conditions must be true
    
    // here's a cursor you can use to fetch your documents
    var cursor = Collection.find(selector);
    
    // log one of the selected documents
    console.log(Collection.findOne(selector));
    

相关问题