mongodb常用语法

// Employee表        
{
    "_id" : "9e794fb9-12dc-457c-8c5a-69fe45c57685",
    "No" : 2018090821,
    "Name" : "Kelly",
    "Age" : 18,
    "Addresses":[
        {"Type" : "Home", "Location" : "Beijing"},
        {"Type" : "Office", "Location" : "Beijing"}
    ]
}

// 分页过滤查找
db.Employee.aggregate([
    { $match:{"Name":"Kelly"}},
    { $project:{"Name":1, "Age":1}},
    { $sort:{"Age":1}},
    { $skip:1000},
    { $limit:30}
],{allowDiskUse:true})

// 查找不在北京工作的员工(数组操作)
db.Employee.aggregate([
    {"$match": {"Type" : "Office", "Addresses": {$not:{$elemMatch:{"Location": "Beijing"}}}}}
],{allowDiskUse:true})

var result = db.Employee.distinct("No", {"Type" : "Office", "Location": "Beijing"})
db.Employee.aggregate([
   {"$match": {"No": {$nin: result}}}
],{allowDiskUse:true})

// 查找在北京工作,且有2个以上住宅的员工
db.Employee.aggregate([
   {"$match": {"Type" : "Office", "Location": "Beijing"}},
   {"$unwind": "$Addresses"},
   {"$match": {"Addresses.Type": "House"}},
   {"$group": {_id: "$No", "count": {"$sum": 1}}},
   {"$match": {"count": {"$gt": 2}}},
   {"sort": {"count":1}}
],{allowDiskUse:true})

// 查找年龄为23-26,名字为Lily或Sam的员工
db.Employee.find({$or:[{"name":"Lily"},{"name":"Sam"}], "Age":{$gte: 23, $lte: 26}}, {"No":1, "Name":1, "_id":0})

select country, province  from dbo.regions group by country, province having count(distinct city)>1 order by country, province 

db.getCollection('dbo.regions').aggregate([
{$group:{_id:{"country" :"$country" ,"province":"$province", "city":"$city"}}}
,{$group:{_id:{"country" :"$_id.country" ,"province":"$_id.province"}, count: {$sum:1}}}
,{$match:{count:{$gt:1}}}
// ,{$project: {"country" :"$_id.country" ,"province":"$_id.province", "_id":0}}
// ,{$sort: {"country" : 1, "province":1}}
// ,{$group:{_id:{"country" :"$country" }, count: {$sum:1}}},
])

转载于:https://www.cnblogs.com/anxiao/p/9354183.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值