mongodb Mongodb查询选择具有给定键的记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4582354/
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 11:54:24  来源:igfitidea点击:

Mongodb Query To select records having a given key

mongodb

提问by Sagar Varpe

The records in my database are

我数据库中的记录是

{"_id":"1","fn":"sagar","ln":"Varpe"}

{"_id":"1","fn":"sag","score":"10"}

{"_id":"1","ln":"ln1","score":"10"}

{"_id":"1","ln":"ln2"} 

I need to design a MongoDB query to find all records that have a given key.

我需要设计一个 MongoDB 查询来查找具有给定键的所有记录。

For example, if I pass lnas a parameter to the query it shuold return all records in which lnis a key. The results would be

例如,如果我ln作为参数传递给查询,它应该返回所有ln作为键的记录。结果将是

{"_id":"1","fn":"sagar","ln":"Varpe"}

{"_id":"1","ln":"ln1","score":"10"}

{"_id":"1","ln":"ln2"} 

回答by Justin Jenkins

To find if a key/field exists in your document use the $existsoperator.

要查找文档中是否存在键/字段,请使用$exists运算符。

Via the MongoDB shell ...

通过 MongoDB 外壳...

db.things.find( { ln : { $exists : true } } );

回答by HADEEL

I had the same problem and

我有同样的问题

db.coll.find({"mykey":{'$exists': 1}})

worked for me

对我来说有效

回答by helpdoc

db.collection.find({ ln: { $exists: true} });

The $size operator matches any array with the number of elements specified by the argument. For example:

$size 运算符匹配具有参数指定的元素数量的任何数组。例如:

db.collection.find({ ln: { $exists: true, $size: 0 } });

$size does not accept ranges of values. To select documents based on fields with different numbers of elements, create a counter field that you increment when you add elements to a field.

$size 不接受值范围。要根据具有不同元素数量的字段选择文档,请创建一个计数器字段,在向字段添加元素时增加该字段。