1. 程式人生 > 資料庫 >MongoDB 常用語句

MongoDB 常用語句

# 批量修改欄位值

db.getCollection('collectiona').find().forEach(
   function(item){                
       db.getCollection('collectiona').update({"_id":item._id},{$set:{"outTradeNo1": 'wzf'+item.title}})
   }
)

 # 批量修改欄位:從另外一張表查詢對應欄位進行更新

var cursor = db.getCollection("qualityInspectionInfo").find({"duration":null});
while (cursor.hasNext()){
  r = cursor.next();
  var resourceInfo  = db.getCollection("resourceInfo").find({"taskId":r['taskId']})[0];
  db.getCollection("qualityInspectionInfo").update({"taskId":r['taskId']},{$set:{"duration":resourceInfo['attr']['duration']}},false,false);
}

# 查詢某欄位的範圍在和不在 

# 查詢特定欄位的取值等於哪些值"$in" ,不等於則用"$nin"
db.getCollection('resourceInfo').find({"attr.channel":"test100","attr.seqNo":{"$in":['000','11133','qqqq']}});

 # 根據時間範圍查詢

db.getCollection('M1SAudioUploadedInfo').find({"seqNo":/^test0915a116.*/,"cloudUploadStatus":{"$in":[0,1,2]},"audioPath":/.mnt.card.test0915a116.*/,
    "createTime" : {"$gte":ISODate("2020-09-18T14:00:00.233+08:00"),"$lt":ISODate("2020-09-18T14:30:00.233+08:00")}}).count()

 # 聚合統計求和

#無查詢條件求欄位和
db.resourceInfo.aggregate( [
   {
     $group: {
        _id: null,total: { $sum: "$attr.duration" }
     }
   }
] );
   
 # 跟進查詢條件求欄位和和資料量 
db.resourceInfo.aggregate( [
                        { $match : { "attr.callType":2,"statisticsStatus" : "1","info.voiceTime" : {"$gte":ISODate("2020-12-26T00:00:00.2000+08:00"), "$lt":ISODate("2020-12-27T00:00:00.2000+08:00")} }},
                        { $group: { _id: null,count: { $sum: 1 },totalTime: { $sum: "$text.totalTime" },validTime: { $sum: "$text.validTime" }}}
                       ] );