MongoDB 对象属性 $ 存在于嵌套数组中 [英] MongoDB object property $exists in nested array

查看:32
本文介绍了MongoDB 对象属性 $ 存在于嵌套数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a folowing object structure in my db collection:

{
    "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"属性可以是空字符串、布尔值、数组,甚至根本没有定义.

So "value" property can be empty string, boolean, array or even not defined at all.

如何查询列出具有非空属性数组且未在数组中的至少一个对象中定义attributes.value"属性的对象?

How can I make query to list objects that have non-empty attributes array and don't have "attributes.value" property defined inside at least one object inside array?

附言我尝试了以下查询:

p.s. I tried following query:

db.collection.find({"attributes": {$exists: true, $ne: []}, "attributes.value": {$exists: false}})

但查询结果为空.

推荐答案

$elemMatch 运算符匹配包含数组字段的文档至少有一个元素匹配所有指定的查询标准.

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 } } 
    }
})

这篇关于MongoDB 对象属性 $ 存在于嵌套数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆