arrays - MongoDB 对象属性 $ 存在于嵌套数组中

标签 arrays mongodb mongoose mongodb-query

我的数据库集合中有一个以下对象结构:

{
    "name" : "test",
    "code" : "test",
    "attributes" : [ 
        {
            "name" : "test1",
            "code" : "code1"
        }, 
        {
            "name" : "test2",
            "code" : "code2",
            "value" : true
        }, 
        {
            "name" : "test3",
            "code" : "code3",
            "value" : ""
        }, 
        {
            "name" : "test4",
            "code" : "code4"
            "value" : [ 
                {
                    "code" : "code4.1",
                    "name" : "test4.1"
                }, 
                {
                    "name" : "test4.2"
                }
            ]
        }
    ]
}

所以“value”属性可以是空字符串、 bool 值、数组,甚至根本没有定义。

如何进行查询以列出具有非空属性数组并且没有在数组中的至少一个对象中定义“attributes.value”属性的对象?

附言我尝试了以下查询:
db.collection.find({"attributes": {$exists: true, $ne: []}, "attributes.value": {$exists: false}})

但查询结果为空。

最佳答案

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.



这个查询对我有用:
db.getCollection('testeur').find({ "attributes": {
        $exists: true, 
        $ne: [],
        $elemMatch: { "value": {$exists: false } } 
    }
})

关于arrays - MongoDB 对象属性 $ 存在于嵌套数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38505816/

相关文章:

javascript - 如何防止向 javascript 数组添加重复键

java - 用范围内的随机数字填充数组

node.js - 从 Node.js 后端向 iPhone 前端发送 JSON 错误 : "Error: Can' t set headers after they are sent. "

mongodb - Meteor.js 和 Mongoose 兼容性

javascript - 如何在 Mongoose 中使用减号按对象属性排序?

javascript - Mongoose: TypeError: 无法读取未定义的属性 'findOne'

java - 数组递增和 i++ 问题

php - 在 PHP 中初始化子数组是否有必要或有用?

node.js - 使用 Mongoose 模式生成假数据

node.js - 使用 Node.JS 从 mongodb 到 MongoLab