$switch
これはMongoDBServer3.4以降の新機能です:
MongoDB Server 3.4 :
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
}
}
});
MongoDB Server 3.2
db.collection('shifts').aggregate([
{
"$match": {
"jobId": ObjectId(job._id),
"from": { "$gte": new Date() }
}
},
{
"$project": {
"hourlyRate": {
"$cond": [
{
"$not": {
"$setIsSubset": [
[{ "$dayOfWeek": "$from" }],
[1, 7]
]
}
}, 20,
{
"$cond": [
{ "$eq": [
{ "$dayOfWeek": "$from" },
7
] },
25,
{
"$cond": [
{ "$eq": [
{ "$dayOfWeek": "$from" },
1
] },
30,
"$hourlyRate"
]
}
]
}
]
}
}
}
], 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
}
}
})