我在NodeJS应用程序中使用MongoDB本机驱动程序。
我的数据库中有一个shifts
集合,我需要更新。我的班次集合中的示例文档
{
"_id" : ObjectId("588425105560bd2ba0065fa4"),
"from" : ISODate("2017-01-23T03:20:00.000Z"),
"to" : ISODate("2017-01-23T06:20:00.000Z"),
"jobId" : ObjectId("586efda790541421b0432897"),
"hourlyRate" : 15
}
{
"_id" : ObjectId("588425105560bd2ba0065fa5"),
"from" : ISODate("2017-01-25T03:20:00.000Z"),
"to" : ISODate("2017-01-25T06:20:00.000Z"),
"jobId" : ObjectId("586efda790541421b0432897"),
"hourlyRate" : 15
}
我需要做的是以下内容 -
更新符合条件的所有文档的hourlyRate
:
hourlyRate
是工作日from
= 20
hourlyRate
是星期六from
= 25
hourlyRate
是星期日from
= 30
我希望尽可能在一个查询中完成。
到目前为止我的解决方案:
使用switch case并使用Date聚合函数中的$dayOfWeek
确定日期类型。但是,我无法将开关与updateMany
组合在一起。
任何帮助都将不胜感激。
答案 0 :(得分:1)
您可以使用特殊运算符运行以下聚合管道,例如 $switch
,这是MongoDB Server 3.4及更高版本中的新增功能:
MongoDB Server 3.4 :
npm ERR! Darwin 15.6.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "protractor"
npm ERR! node v6.9.2
npm ERR! npm v3.10.9
npm ERR! code E404
npm ERR! 404 no such package available : @types/node
npm ERR! 404
npm ERR! 404 '@types/node' is not in the
npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!) npm ERR! 404 It was specified as a dependency of 'protractor'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
npm ERR! Please include the following file with any support request:
MongoDB Server 3.2
db.collection('shifts').aggregate([
{
"$match": {
"jobId": ObjectId(job._id),
"from": { "$gte": new Date() }
}
},
{
"$project": {
"hourlyRate": {
"$switch": {
"branches": [
{
"case": {
"$not": {
"$in": [
{ "$dayOfWeek": "$from" },
[1, 7]
]
}
},
"then": 20
},
{
"case": {
"$eq": [
{ "$dayOfWeek": "$from" },
7
]
},
"then": 25
},
{
"case": {
"$eq": [
{ "$dayOfWeek": "$from" },
1
]
},
"then": 30
}
]
}
}
}
}
], function(err, docs) {
var ops = [],
counter = 0;
docs.forEach(function(doc) {
ops.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": { "$set": { "hourlyRate": doc.hourlyRate } }
}
});
counter++;
if (counter % 500 === 0) {
db.collection('shifts').bulkWrite(ops, function(err, r) {
// do something with result
});
ops = [];
}
})
if (counter % 500 !== 0) {
db.collection('shifts').bulkWrite(ops, function(err, r) {
// do something with result
}
}
});