简体   繁体   English

您如何在 Mongo 中查询“不为空”?

[英]How do you query for "is not null" in Mongo?

I would like to execute a following query:我想执行以下查询:

db.mycollection.find(HAS IMAGE URL)

What should be the correct syntax?正确的语法应该是什么?

This will return all documents with a key called "IMAGE URL", but they may still have a null value.这将返回所有带有一个名为“IMAGE URL”的键的文档,但它们可能仍然有一个空值。

db.mycollection.find({"IMAGE URL":{$exists:true}});

This will return all documents with both a key called "IMAGE URL" and a non-null value.这将返回具有名为“IMAGE URL”的键非空值的所有文档。

db.mycollection.find({"IMAGE URL":{$ne:null}});

Also, according to the docs, $exists currently can't use an index, but $ne can.此外,根据文档, $exists 目前不能使用索引,但 $ne 可以。

Edit: Adding some examples due to interest in this answer编辑:由于对此答案感兴趣,添加了一些示例

Given these inserts:鉴于这些插入:

db.test.insert({"num":1, "check":"check value"});
db.test.insert({"num":2, "check":null});
db.test.insert({"num":3});

This will return all three documents:这将返回所有三个文档:

db.test.find();

This will return the first and second documents only:这将仅返回第一个和第二个文档:

db.test.find({"check":{$exists:true}});

This will return the first document only:这将仅返回第一个文档:

db.test.find({"check":{$ne:null}});

This will return the second and third documents only:这将仅返回第二个和第三个文档:

db.test.find({"check":null})

One liner is the best :一个班轮是最好的:

db.mycollection.find({ 'fieldname' : { $exists: true, $ne: null } });

Here,这里,

mycollection : place your desired collection name mycollection :放置您想要的集合名称

fieldname : place your desired field name fieldname :放置您想要的字段名称

Explaination :说明:

$exists : When is true, $exists matches the documents that contain the field, including documents where the field value is null. $exists :当为真时,$exists 匹配包含该字段的文档,包括字段值为空的文档。 If is false, the query returns only the documents that do not contain the field.如果为 false,则查询仅返回不包含该字段的文档。

$ne selects the documents where the value of the field is not equal to the specified value. $ne选择字段值不等于指定值的文档。 This includes documents that do not contain the field.这包括不包含该字段的文档。

So in your provided case following query going to return all the documents with imageurl field exists and having not null value:因此,在您提供的情况下,以下查询将返回所有具有 imageurl 字段且不具有空值的文档:

db.mycollection.find({ 'imageurl' : { $exists: true, $ne: null } });

In pymongo you can use:在 pymongo 中,您可以使用:

db.mycollection.find({"IMAGE URL":{"$ne":None}});

Because pymongo represents mongo "null" as python "None".因为pymongo将mongo“null”表示为python“None”。

db.collection_name.find({"filed_name":{$exists:true}});

fetch documents that contain this filed_name even it is null.获取包含此字段名称的文档,即使它为空。

Warning警告

db.collection_name.find({"filed_name":{$ne:null}});

fetch documents that its field_name has a value $ne to null but this value could be an empty string also.获取其 field_name 的值 $ne 为 null 但该值也可以是空字符串的文档。

My proposition:我的提议:

db.collection_name.find({ "field_name":{$ne:null},$where:"this.field_name.length >0"})

Sharing for future readers.分享给未来的读者。

This query worked for us (query executed from MongoDB compass ):这个查询对我们有用(从MongoDB compass执行的查询):

{
  "fieldName": {
    "$nin": [
      "",
      null
    ]
  }
}

In an ideal case, you would like to test for all three values , null , "" or empty (field doesn't exist in the record)在理想情况下,您希望测试所有三个null""(记录中不存在字段)

You can do the following.您可以执行以下操作。

db.users.find({$and: [{"name" : {$nin: ["", null]}}, {"name" : {$exists: true}}]})

检查 mongo compass 中是否存在列的最简单方法是:

{ 'column_name': { $exists: true } }

An alternative that has not been mentioned, but that may be a more efficient option for some (won't work with NULL entries) is to use a sparse index (entries in the index only exist when there is something in the field).尚未提及的另一种选择,但对于某些人来说可能是更有效的选择(不适用于 NULL 条目)是使用稀疏索引(索引中的条目仅在字段中有内容时才存在)。 Here is a sample data set:这是一个示例数据集:

db.foo.find()
{ "_id" : ObjectId("544540b31b5cf91c4893eb94"), "imageUrl" : "http://example.com/foo.jpg" }
{ "_id" : ObjectId("544540ba1b5cf91c4893eb95"), "imageUrl" : "http://example.com/bar.jpg" }
{ "_id" : ObjectId("544540c51b5cf91c4893eb96"), "imageUrl" : "http://example.com/foo.png" }
{ "_id" : ObjectId("544540c91b5cf91c4893eb97"), "imageUrl" : "http://example.com/bar.png" }
{ "_id" : ObjectId("544540ed1b5cf91c4893eb98"), "otherField" : 1 }
{ "_id" : ObjectId("544540f11b5cf91c4893eb99"), "otherField" : 2 }

Now, create the sparse index on imageUrl field:现在,在 imageUrl 字段上创建稀疏索引:

db.foo.ensureIndex( { "imageUrl": 1 }, { sparse: true } )
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}

Now, there is always a chance (and in particular with a small data set like my sample) that rather than using an index, MongoDB will use a table scan, even for a potential covered index query.现在,MongoDB 总是有机会(尤其是像我的示例这样的小数据集)而不是使用索引,而是使用表扫描,即使对于潜在的覆盖索引查询也是如此。 As it turns out that gives me an easy way to illustrate the difference here:事实证明,这给了我一个简单的方法来说明这里的区别:

db.foo.find({}, {_id : 0, imageUrl : 1})
{ "imageUrl" : "http://example.com/foo.jpg" }
{ "imageUrl" : "http://example.com/bar.jpg" }
{ "imageUrl" : "http://example.com/foo.png" }
{ "imageUrl" : "http://example.com/bar.png" }
{  }
{  }

OK, so the extra documents with no imageUrl are being returned, just empty, not what we wanted.好的,所以没有imageUrl的额外文档被返回,只是空的,不是我们想要的。 Just to confirm why, do an explain:只是为了确认原因,请解释一下:

db.foo.find({}, {_id : 0, imageUrl : 1}).explain()
{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 6,
    "nscannedObjects" : 6,
    "nscanned" : 6,
    "nscannedObjectsAllPlans" : 6,
    "nscannedAllPlans" : 6,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 0,
    "server" : "localhost:31100",
    "filterSet" : false
}

So, yes, a BasicCursor equals a table scan, it did not use the index.所以,是的, BasicCursor等于表扫描,它没有使用索引。 Let's force the query to use our sparse index with a hint() :让我们强制查询使用带有hint()的稀疏索引:

db.foo.find({}, {_id : 0, imageUrl : 1}).hint({imageUrl : 1})
{ "imageUrl" : "http://example.com/bar.jpg" }
{ "imageUrl" : "http://example.com/bar.png" }
{ "imageUrl" : "http://example.com/foo.jpg" }
{ "imageUrl" : "http://example.com/foo.png" }

And there is the result we were looking for - only documents with the field populated are returned.这就是我们正在寻找的结果——只返回填充了字段的文档。 This also only uses the index (ie it is a covered index query), so only the index needs to be in memory to return the results.这也只使用了索引(即它是一个覆盖索引查询),所以只有索引需要在内存中才能返回结果。

This is a specialized use case and can't be used generally (see other answers for those options).这是一个专门的用例,不能普遍使用(请参阅这些选项的其他答案)。 In particular it should be noted that as things stand you cannot use count() in this way (for my example it will return 6 not 4), so please only use when appropriate.特别应该注意的是,就目前情况而言,您不能以这种方式使用count() (对于我的示例,它将返回 6 而不是 4),因此请仅在适当的时候使用。

db.<collectionName>.find({"IMAGE URL":{"$exists":"true"}, "IMAGE URL": {$ne: null}})

Thanks for providing a solution, I noticed in MQL, sometimes $ne:null doesn't work instead we need to use syntax $ne:"" ie in the context of above example we would need to use db.mycollection.find({"IMAGE URL":{"$ne":""}}) - Not sure why this occurs, I have posted this question in the MongoDB forum.感谢您提供解决方案,我在 MQL 中注意到,有时 $ne:null 不起作用,而是我们需要使用语法 $ne:"" 即在上面示例的上下文中我们需要使用db.mycollection.find({"IMAGE URL":{"$ne":""}}) - 不知道为什么会这样,我已经在 MongoDB 论坛上发布了这个问题。

following is the snapshot showing example:以下是显示示例的快照:

在此处输入图像描述

the Query Will be查询将是

db.mycollection.find({"IMAGE URL":{"$exists":"true"}})

it will return all documents having "IMAGE URL" as a key ...........它将返回所有以“IMAGE URL”为键的文档............

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM