ITPub博客

首页 > 数据库 > NoSQL > mongodb查询

mongodb查询

原创 NoSQL 作者:liiinuuux 时间:2015-04-03 15:42:08 0 删除 编辑
测试数据
> var arr1 = ["aaaa", "bbbb", "cccc", "dddd"];
> var arr2 = ["eeee", "ffff", "gggg", "hhhh"];
> for (var i = 1; i <= 200; i++) {
...    db.user.insert( { x : i, y : [arr1[i%4], arr2[i%4]]} )
... }
WriteResult({ "nInserted" : 1 })

> db.user.findOne({x: 1})
{
        "_id" : ObjectId("54ffb117e9ab791b5d8f85fe"),
        "x" : 1,
        "y" : [
                "bbbb",
                "ffff"
        ]
}

db.user.insert({x: 999, y:["a","b","c","d","e","f"], z:"zzzzzzzzzz"});
db.user.insert({x: 9999, y:[{a: 1}, {b: 2}], z:"zzzzzzzzzz"});
db.user.insert({x: 9999, y:[{a: 10}, {b: 20}], z:"zzzzzzzzzz"});
db.user.insert({x: 9999, y:[{a: 100}, {b: 200}], z:"zzzzzzzzzz"});

查询函数 db.集合名.find()
> db.user.find
function ( query , fields , limit , skip, batchSize, options ){
    var cursor = new DBQuery( this._mongo , this._db , this ,
                        this._fullName , this._massageObject( query ) , fields , limit , skip , batchSize , options || this.getQueryOptions() );

    var connObj = this.getMongo();
    var readPrefMode = connObj.getReadPrefMode();
    if (readPrefMode != null) {
        cursor.readPref(readPrefMode, connObj.getReadPrefTagSet());
    }

    return cursor;
}

查询条件
支持的条件
$eq   =
$gt   >
$gte  >=
$lt   <
$lte  <=
$ne   <>
$in   in
$nin  not in

x大于188
y包含"gggg"
> db.user.find({x:{$gt: 188}, y:"gggg"})
{ "_id" : ObjectId("54ffb16de9ab791b5d8f86bb"), "x" : 190, "y" : [ "cccc", "gggg" ] }
{ "_id" : ObjectId("54ffb16de9ab791b5d8f86bf"), "x" : 194, "y" : [ "cccc", "gggg" ] }
{ "_id" : ObjectId("54ffb16de9ab791b5d8f86c3"), "x" : 198, "y" : [ "cccc", "gggg" ] }

x大于10,小于22
整个y数组是["bbbb", "ffff"]
同时按x倒序排序
输出前2行
> db.user.find({x:{$lt: 22, $lt: 10}, y:{$all: ["bbbb", "ffff"]}}).sort({x: -1}).limit(2)
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8606"), "x" : 9, "y" : [ "bbbb", "ffff" ] }
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8602"), "x" : 5, "y" : [ "bbbb", "ffff" ] }

$all也可以用下面的形式代替
> db.user.findOne({y:["aaaa","eeee"]});
{
        "_id" : ObjectId("54ffb117e9ab791b5d8f8601"),
        "x" : 4,
        "y" : [
                "aaaa",
                "eeee"
        ]
}

"in"条件
> db.user.find({x:{$lt: 10}, y:{$in: ["aaaa", "ffff"]}});
{ "_id" : ObjectId("54ffb117e9ab791b5d8f85fe"), "x" : 1, "y" : [ "bbbb", "ffff" ] }
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8601"), "x" : 4, "y" : [ "aaaa", "eeee" ] }
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8602"), "x" : 5, "y" : [ "bbbb", "ffff" ] }
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8605"), "x" : 8, "y" : [ "aaaa", "eeee" ] }
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8606"), "x" : 9, "y" : [ "bbbb", "ffff" ] }

“或”条件
找出x<5或者x>195的
> db.user.find({$or: [{x:{$lt:5}}, {x:{$gt:195}}]})
{ "_id" : ObjectId("54ffa67be9ab791b5d8f85fd"), "x" : 3 }
{ "_id" : ObjectId("54ffb117e9ab791b5d8f85fe"), "x" : 1, "y" : [ "bbbb", "ffff" ] }
{ "_id" : ObjectId("54ffb117e9ab791b5d8f85ff"), "x" : 2, "y" : [ "cccc", "gggg" ] }
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8600"), "x" : 3, "y" : [ "dddd", "hhhh" ] }
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8601"), "x" : 4, "y" : [ "aaaa", "eeee" ] }
{ "_id" : ObjectId("54ffb16de9ab791b5d8f86c1"), "x" : 196, "y" : [ "aaaa", "eeee" ] }
{ "_id" : ObjectId("54ffb16de9ab791b5d8f86c2"), "x" : 197, "y" : [ "bbbb", "ffff" ] }
{ "_id" : ObjectId("54ffb16de9ab791b5d8f86c3"), "x" : 198, "y" : [ "cccc", "gggg" ] }
{ "_id" : ObjectId("54ffb16de9ab791b5d8f86c4"), "x" : 199, "y" : [ "dddd", "hhhh" ] }
{ "_id" : ObjectId("54ffb16de9ab791b5d8f86c5"), "x" : 200, "y" : [ "aaaa", "eeee" ] }
{ "_id" : ObjectId("550154f11b048c7db6481552"), "x" : 999, "y" : [ "a", "b", "c", "d", "e", "f" ], "z" : "zzzzzzzzzz" }
{ "_id" : ObjectId("550158de3d7e7d39fc067da0"), "x" : 9999, "y" : [ { "a" : 10 }, { "b" : 20 } ], "z" : "zzzzzzzzzz" }
{ "_id" : ObjectId("550158f63d7e7d39fc067da1"), "x" : 9999, "y" : [ { "a" : 100 }, { "b" : 200 } ], "z" : "zzzzzzzzzz" }
{ "_id" : ObjectId("550158fc3d7e7d39fc067da2"), "x" : 9999, "y" : [ { "a" : 1 }, { "b" : 2 } ], "z" : "zzzzzzzzzz" }

查询嵌套文档
完整的
> db.obj.findOne()
{
        "_id" : ObjectId("5502a2ef773fc1f962baf14b"),
        "name" : "obj1",
        "arr" : [
                {
                        "elemName" : "elem1",
                        "elemValue" : 1
                },
                {
                        "elemName" : "elem2",
                        "elemValue" : 2
                }
        ],
        "subObj" : {
                "subName" : "subName1",
                "subArr" : [
                        "subElem1",
                        "subElem2",
                        "subElem3"
                ]
        }
}
按subObj.subName查询。双引号不能省略。
> db.obj.find({"subObj.subName":"subName1"})
{ "_id" : ObjectId("5502a2ef773fc1f962baf14b"), "name" : "obj1", "arr" : [ { "elemName" : "elem1", "elemValue" : 1 }, { "elemName" : "elem2", "elemValue" : 2 } ], "subObj" : { "subName" : "subName1", "subArr" : [ "subElem1", "subElem2", "subElem3" ] } }
按subArr查询
> db.obj.find({"subObj.subArr":"subElem3"})
{ "_id" : ObjectId("5502a2ef773fc1f962baf14b"), "name" : "obj1", "arr" : [ { "elemName" : "elem1", "elemValue" : 1 }, { "elemName" : "elem2", "elemValue" : 2 } ], "subObj" : { "subName" : "subName1", "subArr" : [ "subElem1", "subElem2", "subElem3" ] } }

用正则表达式做条件
找出y包含以多个A开头的元素的记录。正则表达式后面的i意思是不分大小写。
> db.user.find({y: {$regex:/^A+/, $options:"i"}}).limit(1)
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8601"), "x" : 4, "y" : [ "aaaa", "eeee" ] }

也可以简写成:
> db.user.find({y: /^A+/i}).limit(1)
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8601"), "x" : 4, "y" : [ "aaaa", "eeee" ] }

元素以a或A开头,同时不等于aaaa
> db.user.find({y: {$regex:/^A+ #A and a/, $options:"ix", $ne:"aaaa"}}).limit(1)
{ "_id" : ObjectId("550154f11b048c7db6481552"), "x" : 999, "y" : [ "a", "b", "c", "d", "e", "f" ], "z" : "zzzzzzzzzz" }

options包括:
i:不区分大小写
m:如果表达式有^xxx,或者xxx$,如果加上m,则/^x/和/x$/就能匹配aaa\nx和x\naaa这种带换行的情况。
x:让正则表达式可以注释。要用这个选项,必须在find里用$options:x的形式。
    例如
    > var part = "^A #a and A";
    > db.user.find({y: {$regex:part, $options:"ix"}}).limit(1);
    { "_id" : ObjectId("54ffb117e9ab791b5d8f8601"), "x" : 4, "y" : [ "aaaa", "eeee" ] }
s:让符号“.”能也能匹配新一行“\n”。必须在find里用$options:s的形式。


用代码方式自定义判断条件
> db.user.find({$where: "this.x >= 100 && this.y[0] == 'aaaa'"});
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8661"), "x" : 100, "y" : [ "aaaa", "eeee" ] }
{ "_id" : ObjectId("54ffb16de9ab791b5d8f8665"), "x" : 104, "y" : [ "aaaa", "eeee" ] }

最无敌的方式是自己定义函数
> db.user.find({$where:
...   function()
...   {
...     if(this.y == null || this.y == undefined || this.y.length == 0) return false;
...     else if(this.x <= 10 && this.y[1] == 'eeee') return true;
...     else return false;
...   }
... });
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8601"), "x" : 4, "y" : [ "aaaa", "eeee" ] }
{ "_id" : ObjectId("54ffb117e9ab791b5d8f8605"), "x" : 8, "y" : [ "aaaa", "eeee" ] }




字段投影
不包含_id
> db.user.find({x:{$lt: 3}}, { _id: 0})
{ "x" : 1, "y" : [ "bbbb", "ffff" ] }
{ "x" : 2, "y" : [ "cccc", "gggg" ] }

只显示x
> db.user.find({x:{$lt: 3}}, { x:1, _id:0})
{ "x" : 1 }
{ "x" : 2 }

除了x,其它的都显示
> db.user.find({x:{$lt: 3}}, {x:0, _id: 0})
{ "y" : [ "bbbb", "ffff" ] }
{ "y" : [ "cccc", "gggg" ] }

投影里除了_id以外,要么全是1,要么全是0,否则就报错
> db.user.find({x:{$lt: 3}}, {x:0, y:1})
Error: error: {
        "$err" : "Can't canonicalize query: BadValue Projection cannot have a mix of inclusion and exclusion.",
        "code" : 17287
}

对于数组,用$slice控制只返回前几个元素还是后几个元素
返回前面数第一个元素
> db.user.find({x:{$lt: 3}}, {y: {$slice: 1}, x:0, _id: 0})
{ "y" : [ "bbbb" ] }
{ "y" : [ "cccc" ] }
返回后面数第一个元素 
> db.user.find({x:{$lt: 3}}, {y: {$slice: -1}, x:0, _id: 0})
{ "y" : [ "ffff" ] }
{ "y" : [ "gggg" ] }

$slice后面跟数组,可以灵活控制返回哪些数据
先看完整数组
> db.user.find( {x: 999}, {y:1, _id:0})
{ "y" : [ "a", "b", "c", "d", "e", "f" ] }
如果从前面数,就是从0开始,[2,2]的意思是从第3个元素开始,返回2个元素
> db.user.find( {x: 999}, { y: { $slice: [2,2]}, _id:0, x:0, z:0} )
{ "y" : [ "c", "d" ] }
如果是从后面数,就是从-1开始,[-3,2]就是从倒数第3个开始,返回2个元素。
> db.user.find( {x: 999}, { y: { $slice: [-3,2]}, _id:0, x:0, z:0} )
{ "y" : [ "d", "e" ] }


过滤数组里的文档元素
先看完整的
> db.user.find({x:9999}, {z:0, _id:0}).sort({y: 1})
{ "x" : 9999, "y" : [ { "a" : 1 }, { "b" : 2 } ] }
{ "x" : 9999, "y" : [ { "a" : 10 }, { "b" : 20 } ] }
{ "x" : 9999, "y" : [ { "a" : 100 }, { "b" : 200 } ] }
只显示包含{a:10}的y
> db.user.find({x:9999}, {y:{$elemMatch:{a:10}}, z:0, _id:0})
{ "x" : 9999, "y" : [ { "a" : 10 } ] }
{ "x" : 9999 }
{ "x" : 9999 }













来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/26239116/viewspace-1485417/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: mongodb索引
请登录后发表评论 登录
全部评论

注册时间:2012-11-12

  • 博文量
    94
  • 访问量
    353434