在 MongoDB 中查询具有给定属性集的文档
Query for documents with given set of attributes in MongoDB
我正在 mongo.exe 中编写如下查询:
db.sheep.find( { "timestamp" : {
"$gt":ISODate("2015-05-15T10:00:00.000z"),
"$lt":ISODate("2015-05-15T10:05:10.000z") } },
{"x":1,"y":1,"z":1,"timestamp":1})
但是,一些 returned 文档有 timestamp
但没有 x
、y
、z
。我如何 return 仅包含 timestamp
和 x y z
的文档?
我想有一些非常简单的逻辑可以添加到查询中,但我四处搜索时似乎找不到任何东西。
您可以使用 $exists
运算符。
db.sheep.find(
{
"timestamp" : {
"$gt":ISODate("2015-05-15T10:00:00.000z"),
"$lt":ISODate("2015-05-15T10:05:10.000z")
},
"x": { "exists": true },
"y": { "exists": true },
"z": { "exists": true }
},
{"x":1,"y":1,"z":1,"timestamp":1})
第一个参数,过滤器对象,确定匹配项必须满足的条件。在这种情况下,时间戳必须在一定的时间间隔内。
第二个参数是一个投影,主要用于删除不需要的字段,尤其是当数据很大时(比如一些嵌入式二进制文档、文件或其他东西)。
如果您想确保文档设置了 x
、y
和 z
,您可以使用 $exists
:
进行检查
db.sheep.find(
{
"timestamp" : {
"$gt" : ISODate("2015-05-15T10:00:00.000z"),
"$lt" : ISODate("2015-05-15T10:05:10.000z")
},
"x": { "$exists": true },
"y": { "$exists": true },
"z": { "$exists": true }
});
但是,请注意,这通常是 错误架构设计 的标志。 $exists
,根据定义,具有最坏情况的选择性,因此不要指望这些查询很快。
我正在 mongo.exe 中编写如下查询:
db.sheep.find( { "timestamp" : {
"$gt":ISODate("2015-05-15T10:00:00.000z"),
"$lt":ISODate("2015-05-15T10:05:10.000z") } },
{"x":1,"y":1,"z":1,"timestamp":1})
但是,一些 returned 文档有 timestamp
但没有 x
、y
、z
。我如何 return 仅包含 timestamp
和 x y z
的文档?
我想有一些非常简单的逻辑可以添加到查询中,但我四处搜索时似乎找不到任何东西。
您可以使用 $exists
运算符。
db.sheep.find(
{
"timestamp" : {
"$gt":ISODate("2015-05-15T10:00:00.000z"),
"$lt":ISODate("2015-05-15T10:05:10.000z")
},
"x": { "exists": true },
"y": { "exists": true },
"z": { "exists": true }
},
{"x":1,"y":1,"z":1,"timestamp":1})
第一个参数,过滤器对象,确定匹配项必须满足的条件。在这种情况下,时间戳必须在一定的时间间隔内。
第二个参数是一个投影,主要用于删除不需要的字段,尤其是当数据很大时(比如一些嵌入式二进制文档、文件或其他东西)。
如果您想确保文档设置了 x
、y
和 z
,您可以使用 $exists
:
db.sheep.find(
{
"timestamp" : {
"$gt" : ISODate("2015-05-15T10:00:00.000z"),
"$lt" : ISODate("2015-05-15T10:05:10.000z")
},
"x": { "$exists": true },
"y": { "$exists": true },
"z": { "$exists": true }
});
但是,请注意,这通常是 错误架构设计 的标志。 $exists
,根据定义,具有最坏情况的选择性,因此不要指望这些查询很快。