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})
相關文章
相關標籤/搜索