mongo常用查询
基础
以下使用userEntity当作表明
查询姓名等于张三的用户
db.userEntity.find({name:'张三'})
查询年龄大于等与10的用户
db.userEntity.find({age:{$gte:10}})
查询年龄小于等与10的用户
db.userEntity.find({age:{$lte:10}})
查询名字等于张三并且年龄大于等于10的用户
db.userEntity.find({age:{$gte:10},name:'张三'})
查询年龄大于等与10或者姓名等于张三的用户
db.userEntity.find({ $or: [{'age':{$gte : 10 }},{'name':'张三'}]})
模糊查询姓名包含张三的用户
db.userEntity.find({{'name':/张三/})
模糊查询姓名以张三开头的用户
db.userEntity.find({{'name':/^张三/})
模糊查询姓名以张三结尾的用户
db.userEntity.find({{'name':/张三/})
统计姓名为张三的用户数量
db.userEntity.find({{'name':'张三'}).count()
返回固定字段name、age、birthday
db.userEntity.find({{'name':'张三'},{name:1,age:1,birthday:1})
返回固定字段
db.userEntity.find({{'name':'张三'},{name:1,age:1,birthday:1})
in查询
db.userEntity.find({{'name':{$in:['张三','李四','王五']}})
in查询
db.userEntity.find({{'name':{$in:['张三','李四','王五']}})
升序
db.userEntity.find().sort({"age":1});
降序
db.userEntity.find().sort({"age":-1});
进阶
联表查询、组合复杂查询
查询机构部门、树形结构查询
var parentId= "5c0e33b9c80d5897fd70b11d";
db.getCollection('resourceGroupEntity').find({
parentId: parentId
}).forEach(function(org) {
print(org.name)
db.getCollection('resourceGroupEntity').find({"parentId" : org._id.str}).forEach(function(org2) {
print(" "+org2.name)
db.getCollection('resourceGroupEntity').find({"parentId" : org2._id.str,name:/客户服务中心/}).forEach(function(org3) {
db.getCollection('userEntity').find({'attrs.stell':'48010238',groupIds:{$in:[org3._id.str]}}).forEach(function(usr) {
print(" "+org.name + "-" +org2.name + "-" +org3.name + "," + usr.displayName + "," + usr.username)
})
})
})
})