检查字段是否存在于 MongoDB
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19868016/
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
Check that Field Exists with MongoDB
提问by AlbertEngelB
So I'm attempting to find all records who have a field set and isn't null.
所以我试图找到所有具有字段集且不为空的记录。
I try using $exists
, however according to the MongoDB documentation,this query will return fields who equal null.
我尝试使用$exists
,但是根据MongoDB 文档,此查询将返回等于 null 的字段。
$exists
does match documents that contain the field that stores the null value.
$exists
匹配包含存储空值的字段的文档。
So I'm now assuming I'll have to do something like this:
所以我现在假设我必须做这样的事情:
db.collection.find({ "fieldToCheck" : { $exists : true, $not : null } })
Whenever I try this however, I get the error [invalid use of $not]
Anyone have an idea of how to query for this?
然而,每当我尝试这样做时,我都会收到错误消息[invalid use of $not]
有人知道如何查询吗?
回答by Sergio Tulentsev
Use $ne
(for "not equal")
使用$ne
(用于“不等于”)
db.collection.find({ "fieldToCheck": { $exists: true, $ne: null } })
回答by Pavan Choudhary
Suppose we have a collection like below:
假设我们有一个像下面这样的集合:
{
"_id":"1234"
"open":"Yes"
"things":{
"paper":1234
"bottle":"Available"
"bottle_count":40
}
}
We want to know if the bottle field is present or not?
我们想知道瓶子字段是否存在?
Ans:
答:
db.products.find({"things.bottle":{"$exists":true}})
回答by Yakir Manor
i find that this works for me
我发现这对我有用
db.getCollection('collectionName').findOne({"fieldName" : {$ne: null}})