mongodb常用的查询sql语句总结

本文为博主原创,转载请注明出处:

1. 查询所有

db.getCollection('CollectionName').find()

2.根据条件查询

db.getCollection('CollectionName').find({"userId":37761});

3.多条件查询

db.getCollection('CollectionName').find({"userId":1},{"customerId":61});

4.根据时间戳范围查询

db.getCollection('CollectionName').find({"userId":61},{"timestamp":{"$gt":1540449300000,"$lte":1540550100000}})

5.条件查排序并分页:1.是升序,  -1是降序 

db.getCollection('CollectionName').find({"userId":361}).sort({"time":-1}).limit(100);

6.多条件查询

#第一种写法
db.getCollection('CollectionName').find( {$and:[{"userId":37761},{"domain":"time.com"},{"timestamp":{"$gt":1540483200000,"$lte":1540550100000}}]});

#第二种写法
db.getCollection('CollectionName').find( {"userId":37761,"domain":"time.com","timestamp":{"$gt":1540483200000,"$lte":1540550100000}});

mongodb中对应的范围标识符:

"$lt"===================>  "<"
"$lte"==================>  "<="
"$gt"===================>  ">"
"$gte"==================>  ">="
"$ne"===================>  "!="

7.ISOdate时间范围查询

db.getCollection('CollectionName').find({ "timestamp" : { "$gte" : ISODate("2018-04-20T00:00:00Z"), "$lt" : ISODate("2018-04-21T00:00:00Z") }});

8.获取记录总数

db.student.find().count()

9.查看去重字段

db.student.distinct('name')

10.查询条件字段不为空

db.student.find({"student":{"$ne":null, $exists:true}});

11.查询只展示指定的字段

db.student.find({"name": { $regex: "^.*大.*$"},"classId" : "cebdcaa93722c557ee35ade3e8005676"},{"name": 1})

  根据条件查询,只展示 name字段

  默认会显示 _id ; 1 表示显示此字段; 0 表示不显示此字段

  假设有一个名为users的集合,其中包含_idnameage三个字段。如果只想查询name字段,可以这样写MongoDB查询:

db.users.find({}, { name: 1, _id: 0 })

12.限制查询数量

db.users.find().skip(10).limit(5)

13.模糊查询

db.getCollection('student').find({"uid":"1588", "nick":{$elemMatch: { $regex: "哈哈"}} });

db.getCollection('student').find({"nick": { $regex: "^.*哥哥.*$"},"uid":"1588"} );

 

mongodb 可视化工具 robo 3t

 

posted @ 2019-04-12 20:52  香吧香  阅读(9855)  评论(0编辑  收藏  举报