[304]mongodb查询的语法总结

  1. 大于,小于,大于或等于,小于或等于

$gt:大于
$lt:小于
$gte:大于或等于
$lte:小于或等于

例子:

db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value
db.collection.find({ "field" : { $lt: value } } ); // less than : field < value
db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value
db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value

如查询j大于3,小于4:

db.things.find({j : {$lt: 3}});
db.things.find({j : {$gte: 4}});
也可以合并在一条语句内:
db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
  1. 不等于 $ne

例子:

db.things.find( { x : { $ne : 3 } } );
  1. in 和 not in ($in $nin)

语法:

db.collection.find( { "field" : { $in : array } } );

例子:

db.things.find({j:{$in: [2,4,6]}});
db.things.find({j:{$nin: [2,4,6]}});
  1. 取模运算$mod

如下面的运算:

db.things.find( "this.a % 10 == 1")
可用$mod代替:
db.things.find( { a : { $mod : [ 10 , 1 ] } } )
  1. $all

$all和$in类似,但是他需要匹配条件内所有的值:

如有一个对象:{ a: [ 1, 2, 3 ] }
下面这个条件是可以匹配的:

db.things.find( { a: { $all: [ 2, 3 ] } } );

但是下面这个条件就不行了:

db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
  1. $size

$size是匹配数组内的元素数量的,如有一个对象:{a:[“foo”]},他只有一个元素:

下面的语句就可以匹配:db.things.find( { a : { $size: 1 } } );

官网上说不能用来匹配一个范围内的元素,如果想找$size<5之类的,他们建议创建一个字段来保存元素的数量。

You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements.

7)$exists

$exists用来判断一个元素是否存在:

如:

db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
  1. $type

$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。

db.things.find( { a : { $type : 2 } } ); // matches if a is a string
db.things.find( { a : { $type : 16 } } ); // matches if a is an int

9)正则表达式

mongo支持正则表达式,如:

db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
  1. 查询数据内的值

下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。

db.things.find( { colors : "red" } );
  1. $elemMatch

如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:

> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 
{ "_id" : ObjectId("4b5783300334000000000aa9"), 
"x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
}$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。

注意,上面的语句和下面是不一样的。

> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
  1. 查询嵌入对象的值
db.postings.find( { "author.name" : "joe" } );

注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation

举个例子:

db.blog.save({ title : “My First Post”, author: {name : “Jane”, id : 1}})

如果我们要查询 authors name 是Jane的, 我们可以这样:

db.blog.findOne({“author.name” : “Jane”})

如果不用点,那就需要用下面这句才能匹配:

db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})

下面这句:

db.blog.findOne({"author" : {"name" : "Jane"}})

是不能匹配的,因为mongodb对于子对象,他是精确匹配。

  1. 元操作符 $not 取反

如:

db.customers.find( { name : { $not : /acme.*corp/i } } );
db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } ); 

mongodb还有很多函数可以用,如排序,统计等,请参考原文。
mongodb目前没有或(or)操作符,只能用变通的办法代替。

左边是mongodb查询语句,右边是sql语句。对照着用,挺方便。  
db.users.find() select * from users  
db.users.find({"age" : 27}) select * from users where age = 27  
db.users.find({"username" : "joe", "age" : 27}) select * from users where "username" = "joe" and age = 27  
db.users.find({}, {"username" : 1, "email" : 1}) select username, email from users  
db.users.find({}, {"username" : 1, "_id" : 0}) // no case  // 即时加上了列筛选,_id也会返回;必须显式的阻止_id返回  
db.users.find({"age" : {"$gte" : 18, "$lte" : 30}}) select * from users where age >=18 and age <= 30 // $lt(<) $lte(<=) $gt(>) $gte(>=)  
db.users.find({"username" : {"$ne" : "joe"}}) select * from users where username <> "joe"  
db.users.find({"ticket_no" : {"$in" : [725, 542, 390]}}) select * from users where ticket_no in (725, 542, 390)  
db.users.find({"ticket_no" : {"$nin" : [725, 542, 390]}}) select * from users where ticket_no not in (725, 542, 390)  
db.users.find({"$or" : [{"ticket_no" : 725}, {"winner" : true}]}) select * form users where ticket_no = 725 or winner = true  
db.users.find({"id_num" : {"$mod" : [5, 1]}}) select * from users where (id_num mod 5) = 1  
db.users.find({"$not": {"age" : 27}}) select * from users where not (age = 27)  
db.users.find({"username" : {"$in" : [null], "$exists" : true}}) select * from users where username is null // 如果直接通过find({"username" : null})进行查询,那么连带"没有username"的纪录一并筛选出来  
db.users.find({"name" : /joey?/i}) // 正则查询,value是符合PCRE的表达式  
db.food.find({fruit : {$all : ["apple", "banana"]}}) // 对数组的查询, 字段fruit中,既包含"apple",又包含"banana"的纪录  
db.food.find({"fruit.2" : "peach"}) // 对数组的查询, 字段fruit中,第3个(从0开始)元素是peach的纪录  
db.food.find({"fruit" : {"$size" : 3}}) // 对数组的查询, 查询数组元素个数是3的记录,$size前面无法和其他的操作符复合使用  
db.users.findOne(criteria, {"comments" : {"$slice" : 10}}) // 对数组的查询,只返回数组comments中的前十条,还可以{"$slice" : -10}, {"$slice" : [23, 10]}; 分别返回最后10条,和中间10条  
db.people.find({"name.first" : "Joe", "name.last" : "Schmoe"})  // 嵌套查询  
db.blog.find({"comments" : {"$elemMatch" : {"author" : "joe", "score" : {"$gte" : 5}}}}) // 嵌套查询,仅当嵌套的元素是数组时使用,  
db.foo.find({"$where" : "this.x + this.y == 10"}) // 复杂的查询,$where当然是非常方便的,但效率低下。对于复杂查询,考虑的顺序应当是 正则 -> MapReduce -> $where  
db.foo.find({"$where" : "function() { return this.x + this.y == 10; }"}) // $where可以支持javascript函数作为查询条件  
db.foo.find().sort({"x" : 1}).limit(1).skip(10); // 返回第(10, 11]条,按"x"进行排序; 三个limit的顺序是任意的,应该尽量避免skip中使用large-number  

使用 $where 查询(性能稍逊一些)

//查询商品名称长度大于25个字符的商品
db.item.find({item_name:{$exists:true},$where:"(this.item_name.length > 25)"}).limit(5)
 
//查询商品名称长度小于5个字符的商品
db.item.find({$where:"this.item_name.length < 5"}).limit(5)

使用正则表达式查询(性能比$where 高)

//查询商品名称长度大于25个字符的商品
db.item.find({"item_name": {"$exists": true, "$regex": /^.{25,}$/}}).limit(5)   // 长度大于25
 
//查询商品名称长度小于5个字符的商品
db.item.find({"item_name": {"$regex": /^.{0,5}$/}}).limit(5)

mongo 去除指定字段值重复的数据

mongodb 中 distinct 的作用是:获取集合中指定字段的不重复值,并以数组的形式返回

语法:

db.collection_name.distinct(field,query,options)

field——指定要返回的字段(String)

query——条件查询(document)

options——其他选项(document)

例如:

{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] } 
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] } 
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }

db.inventory.distinct(“dept”) //获取dept字段的不重复值

结果:[“A”,“B”]

db.inventory.distinct(“item.sku”) //获取item子字段sku的不重复值

结果:[“111”,“222”,“333”]

db.inventory.distinct(“item.sku”,{dept:“A”}) //满足dept为A的item子字段sku的不重复值

结果:[“111”,“333”]

但是distinct只能获取不重复值,不能去除重复项,保留不重复记录

以下方法去除重复项:

进入mongo命令,切换至指定数据库use databaseName,具体命令可参考https://blog.csdn.net/cat_book_milk/article/details/79161720


>var obj1 = db.test.find({"field_name":""});//此处可添加查询条件
>while(obj1.hasNext()){
    var obj2 = db.test.find();
    var doc1 = obj1.next();
    while(obj2.hasNext()){
        var doc2 = obj2.next();
        if(doc1.fieldName == doc2.fieldName){
            db.test.remove({"fieldName":doc1.fieldName});
        }
    }
    db.test.insert(doc1);

参考:http://blog.163.com/ji_1006/blog/static/10612341201311271384351/
https://blog.csdn.net/qq_27093465/article/details/51700435
https://blog.csdn.net/cat_book_milk/article/details/82463549

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小董

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值