MongoDB - 检查文档中某个字段的值是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22367335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:37:48  来源:igfitidea点击:

MongoDB - Check if value exists for a field in a document

mongodbmongodb-query

提问by Pi Horse

I have a collection where the document looks like below:

我有一个集合,其中的文档如下所示:

/* 0 */

{
    "_id" : ObjectId("5320b1c723bc746084fa7107"),
    "channels" : [ 
        3, 
        4
    ]
}


/* 1 */

{
    "_id" : ObjectId("5320b1c723bc746084fa7107"),
    "channels" : [ ]
}

I want to form a query such that I want all documents where channels has some value and is not empty.

我想形成一个查询,以便我想要所有通道具有某些值且不为空的文档。

I tried this:

我试过这个:

db.event_copy.find({"channels":{$exists:true}})

But that will still return me the documents with no values in channel.

但这仍然会返回通道中没有值的文档。

采纳答案by Pi Horse

I did it using this :

我是用这个做的:

db.event_copy.find({'channels.0' : {$exists: true}}).count()

回答by Neil Lunn

You need the $sizeoperator. To find something with noelements do the following

您需要$size运算符。要找到没有元素的东西,请执行以下操作

db.collection.find({ channels: {$size: 0} })

If you know you have a fixed size then do that

如果你知道你有一个固定的尺寸,那么就这样做

db.collection.find({ channels: {$size: 2} })

Otherwise reverse that with $not

否则用$not反转它

db.collection.find({ channels: {$not:{$size: 0}} })

And you can combine with $and:

你可以结合$and

db.collection.find({ $and: [ 
    { channels: {$not:{$size: 0}} },
    { channels: {$exists: true } }
]})

回答by Anand Jayabalan

Check out the size operator here

在此处查看尺寸运算符

db.event_copy.find( { channels: { $size: 0 } } );