MongoDB查询

来源:互联网 发布:数据信息加工 编辑:程序博客网 时间:2024/05/18 21:42
$lt       <
$lte     <=
$gt      >
$gte    >=
 
> db.foobar.find({"age":{"$gte":17,"$lte":28}})
{ "_id" : ObjectId("53bcda12683a68fb76101911"), "name" : "daiweiwei", "age" : 17 , "score" : 33 } 
{ "_id" : ObjectId("53bd0ccc683a68fb76101912"), "name" : "dai2", "age" : 27, "ge nder" : "男" }

$in,$nin

> db.users.find({"age":{$in:[15,16]}})
{ "_id" : ObjectId("53bd2a21772f0712c3af9044"), "name" : "daiweiwei", "age" : 15 , "sex" : "男" } 
{ "_id" : ObjectId("53bd2a21772f0712c3af9045"), "name" : "daiweiwei", "age" : 16 , "sex" : "男" }

$not

$mod
> db.users.find({"age":{$mod:[11,1]}})
{ "_id" : ObjectId("53bd2a21772f0712c3af9036"), "name" : "daiweiwei", "age" : 1,
 "sex" : "男" }
{ "_id" : ObjectId("53bd2a21772f0712c3af9041"), "name" : "daiweiwei", "age" : 12
, "sex" : "男" }

$slice 返回数组的一个子集合
 --通过$slice返回数组中的部分数据。"$slice":2表示数组中的前两个元素。
    > db.test.find({},{"fruit": {"$slice":2}, "size":0})
    { "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "apple", "kumquat" ]}
    { "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "cherry", "banana" ]} 
    --通过$slice返回数组中的部分数据。"$slice":-2表示数组中的后两个元素。
    > db.test.find({},{"fruit": {"$slice":-2}, "size":0})
    { "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "orange", "strawberry" ] }
    { "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "apple", "strawberry" ] }
    --$slice : [2,1],表示从第二个2元素开始取1个,如果获取数量大于2后面的元素数量,则取后面的全部数据。
    > db.test.find({},{"fruit": {"$slice":[2,1]}, "size":0})
    { "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "orange" ] }
    { "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "apple" ] }

$elemMatch,正确指定某个条件,而不用指定每个键

不能直接用db.blog.find({"comments":{"author":"joe","score":{$gte:5}}})来查询,内嵌文档匹配要求整个文档完全匹配,而这没有匹配comment
          使用db.blog.find({"comments.author":"joe","comments.score":{$gte:5}}),同样也不会达到目的,
> db.foobar.find({},{"age":1})
{ "_id" : ObjectId("53bcbcdf683a68fb76101910"), "age" : 50 }
{ "_id" : ObjectId("53bcda12683a68fb76101911"), "age" : 17 }
> db.foobar.find({},{"age":1,"name":1}) 
{ "_id" : ObjectId("53bcbcdf683a68fb76101910"), "age" : 50 }
{ "_id" : ObjectId("53bcda12683a68fb76101911"), "name" : "daiweiwei", "age" : 17 }

不返回某键
> db.foobar.find({},{"_id":0}) 
{ "age" : 50, "relationships" : { "friends" : 27, "enemies" : 50 } }
{ "name" : "daiweiwei", "age" : 17, "score" : 33 }


0 0