作者:静雨2502874293 | 来源:互联网 | 2014-05-28 16:53
首先我们先插入几个文档db.food.insert({“_id”:1,“fruit”:[apple,banana,peach]})db.food.insert({“_id”:2,“fruit”:[apple,kumquat,orange]})db.food.insert({“_id”:3,“fruit”:[cherry
首先我们先插入几个文档
> db.food.insert({“_id”:1,
“fruit”:["apple","banana","peach"]})
> db.food.insert({“_id”:2,
“fruit”:["apple","kumquat","orange"]})
> db.food.insert({“_id”:3,
“fruit”:["cherry","banana","apple"]})
我们想要查询既包含”apple”并且又包含”banana”的文档,就需要使用”$all“来查询
> db.food.find({“fruit”:{“$all”:["apple","banana"]}})
{ “_id” : 1, “fruit” : [ "apple", "banana", "peach" ]
}
{ “_id” : 3, “fruit” : [ "cherry", "banana", "apple" ]
}
还记得之前的”$in“吗,如果我们需要查询包含”apple”或者”banana”的文档,则使用”$in”
> db.food.find({“fruit”:{“$in”:["apple","banana"]}})
{ “_id” : 1, “fruit” : [ "apple", "banana", "peach" ]
}
{ “_id” : 2, “fruit” : [ "apple", "kumquat", "orange" ]
}
{ “_id” : 3, “fruit” : [ "cherry", "banana", "apple" ]
}
使用”$size“可以查询指定长度的数组
> db.food.find({“fruit”:{$size:3}})
{ “_id” : 1, “fruit” : [ "apple", "banana", "peach" ]
}
{ “_id” : 2, “fruit” : [ "apple", "kumquat", "orange" ]
}
{ “_id” : 3, “fruit” : [ "cherry", "banana", "apple" ]
}
使用”$slice“返回数组中的一个子集合
> db.blog.findOne()
{
”_id” :
ObjectId(“4e914ad2717ed94f8289ac08″),
”comments” : [
{
"name" :
"joe",
"email" :
"joe@example.com",
"content" : "good
blog"
},
{
"content" : "Changed
Comment",
"email" :
"john@gmail.com",
"name" :
"john"
},
{
"name" :
"test",
"email" :
"test@test.com",
"content" :
"test"
},
{
"name" :
"test1",
"email" :
"test1@test.com",
"content" :
"test1"
},
{
"name" :
"test12",
"email" :
"test12@test.com",
"content" :
"test12"
},
{
"name" :
"test123",
"email" :
"test123@test.com",
"content" :
"test123"
}
],
”content” : “My first
blog.”,
”title” : “Hello
World”
}
需要返回comments中的前两条数据,如下查询语句
> db.blog.findOne({},{“comments”:{$slice:2}})
{
”_id” :
ObjectId(“4e914ad2717ed94f8289ac08″),
”comments” : [
{
"name" :
"joe",
"email" :
"joe@example.com",
"content" : "good
blog"
},
{
"content" : "Changed
Comment",
"email" :
"john@gmail.com",
"name" :
"john"
}
],
”content” : “My first
blog.”,
”title” : “Hello
World”
}
查询comments中后两条数据的查询语句:
> db.blog.findOne({},{“comments”:{$slice:-2}})
还可以返回跳过几个文档之后的几个文档
> db.blog.findOne({},{“comments”:{$slice:[1,2]}})
{
”_id” :
ObjectId(“4e914ad2717ed94f8289ac08″),
”comments” : [
{
"content" : "Changed
Comment",
"email" :
"john@gmail.com",
"name" :
"john"
},
{
"name" :
"test",
"email" :
"test@test.com",
"content" :
"test"
}
],
”content” : “My first
blog.”,
”title” : “Hello
World”
}