MongoDB的查询数组

MongoDB查询数组学习笔记
首先我们先插入几个文档

> 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":"[email protected]",
            "content":"good blog"
        },
        {
            "content":"Changed Comment",
            "email":"[email protected]",
            "name":"john"
        },
        {
            "name":"test",
            "email":"[email protected]",
            "content":"test"
        },
        {
            "name":"test1",
            "email":"[email protected]",
            "content":"test1"
        },
        {
            "name":"test12",
            "email":"[email protected]",
            "content":"test12"
        },
        {
            "name":"test123",
            "email":"[email protected]",
            "content":"test123"
        }
    ],
    ”content:My first blog.”,
    ”title:HelloWorld
}

需要返回comments中的前两条数据,如下查询语句


> db.blog.findOne({},{“comments”:{$slice:2}})
{
    ”_id:ObjectId(“4e914ad2717ed94f8289ac08″),
    ”comments:[
        {
            "name":"joe",
            "email":"[email protected]",
            "content":"good blog"
        },
        {
            "content":"Changed Comment",
            "email":"[email protected]",
            "name":"john"
        }
    ],
    ”content:My first blog.”,
    ”title:HelloWorld
}

查询comments中后两条数据的查询语句:

> db.blog.findOne({},{“comments”:{$slice:-2}})

还可以返回跳过几个文档之后的几个文档


> db.blog.findOne({},{“comments”:{$slice:[1,2]}})
{
    ”_id:ObjectId(“4e914ad2717ed94f8289ac08″),
    ”comments:[
        {
            "content":"Changed Comment",
            "email":"[email protected]",
            "name":"john"
        },
        {
            "name":"test",
            "email":"[email protected]",
            "content":"test"
        }
    ],
    ”content:My first blog.”,
    ”title:HelloWorld
}

常用:

1,db.items.find({itemId:201372979046})

2,可用Robomongo软件做可视化查询。

3,查询collections用命令Show collections

 

猜你喜欢

转载自lg985.iteye.com/blog/2277221
今日推荐