1.mongodb安裝
-
下載和安裝
下載地址:https://www.mongodb.com/download-center#community
新建目錄:c:\data\db>。(用來存儲數據)
從MongoDB目錄的bin目錄中執行mongod.exe文件。
mongod.exe --dbpath c:\data\db
mongodb成功開啟:
默認配置:
host:127.0.0.1
port:27017
- 修改配置
- mongobooster
鏈接:http://pan.baidu.com/s/1jHHG5zK 密碼:3pbi
2.{ read: 'secondaryPreferred' , bufferCommands: false}
//API調用記錄
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
//API舊庫
var conn = mongoose.createConnection("mongodb://");
var apicallhistorySchema = mongoose.Schema({
user_id: { type: String, index: true },
product_name: { type: String },
}, { read: 'secondaryPreferred' , bufferCommands: false});
module.exports = conn.model('apicallhistories', apicallhistorySchema);
secondaryPreferred:讀寫分離;
bufferCommands:等待太久,沒有then,也沒有catch,false,等待太久,強制結束,throw err。
3.aggregate管道聚合
var date = new Date('2017-2-22');
var time = new Date('2017-2-1');
db.apicallhistories.aggregate(
[
{ $match : { created_date : { $gt :time ,$lte : date} } },
{$group:{_id :{user_id:"$user_id",method_name:"$method_name",status:"$status"},count:{$sum:1},
totalcost:{$sum:"$cost"},avg_timespent:{$avg:"$time_spent"},max_timespent:{$max:"$time_spent"},min_timespent:{$min:"$time_spent"}
}}
]
)
4.find
- licenses_alls字段存在
db.enterprises.find({licenses_alls:{$elemMatch:{$ne:null}}})
db.enterprises.find({licenses_alls:{$ne:null}})
- licenses_alls字段不存在
db.enterprises.find({judicial_freezes_alls:null})
- licenses_alls字段存在,但是為空數組
db.enterprises.find({judicial_freezes_alls:{"$size":0}})
- 包括null和沒有這個字段
db.C.find({"c":null})
- 僅僅null
db.C.find({"c":{"$in":[null],"$exists":true}})
5.update
- 更新滿足條件的多條記錄
db.batchjobhistories.updateMany({name:"apiHistoriesToOts(test)"},{$set:{milestone:""}},{ multi: true,upsert: false});
-
更新滿足條件的一條記錄
db.batchjobhistories.update({name:"apiHistoriesToOts(test)"},{$set:{milestone:""}},{ multi: true,upsert: false});
- **更新滿足多個件的記錄**
var arr = ["56dd8ea15288f730bda692a2",
"56dd8ea15288f730bda692a7",
"56dd8f735288f730bda692a8",
"56dd8f954c6880c8b99787c7"]
db.apiwritefailedhistories.update( { "id" : {$in: arr}} , { $set : { "condition" : "true"} }, {upsert: true} )
#####5.$and、$or
db.enterprises.find({},{$or: [{resolveStatus: "待處理"}, {resolveStatus: "已完成"}], $and: [{zentao_task_id: {$ne: null}}, {zentao_task_id: {$ne: ""}}]})