猫鼬。查询对象数组中不存在特定值的文档

时间:2017-08-17 16:44:42

标签: arrays node.js mongodb mongoose

型号:

var UserSchema = new Schema({
    username: String,
    userLog: [
        {
            name: String,
            logflag: Boolean,
            logTime: Date
        }
    ],
});

mongoose.model('User', UserSchema);

样本文件:

{
    "name" : User_1,
    "userLog" : [ 
        {
            "_id" : ObjectId("598ac4ac4cd6945012e3eac9"),   
            "name" : "Start",
            "logflag" : true,
            "logTime" : "06:00"
        }, 
        {
            "_id" : ObjectId("598ac4ac4cd6945012e3eaca"),
            "name" : "Mid Day",     
            "logTime" : "12:00",
            "logflag" : false
        }, 
        {
            "_id" : ObjectId("598ac4ac4cd6945012e3eacb"),
            "name" : "End",
            "logflag" : false,      
            "logTime" : "18:00"
        }
    ]
},
{
    "name" : User_2,
    "userLog" : [ 
        {
            "_id" : ObjectId("5989c1ec498267d015ca33c9"),
            "name" : "Start",
            "logflag" : true,       
            "logTime" : "18:00"
        },
        {
            "_id" : ObjectId("5989c1ec498267d015ca33ca"),
            "name" : "End", 
            "logflag" : true,       
            "logTime" : "06:00"
        }   
    ]
}

我正在寻找一个检索具有 ALL ' logflags'设置为true(或 NO logflag设置为false)。该数组具有可变数量的对象。

在上面的示例中,查询将返回User_2。

我尝试了以下内容:

User.find({ "userLog.logflag": {$ne: false}})

哪个不起作用。

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您必须更改查询

User.find({ "userLog": {$elemMatch: { logflag: true}}})