आप अपने निपटान में विशेष ऑपरेटरों के साथ निम्नलिखित एकत्रीकरण पाइपलाइन चला सकते हैं जैसे $switch
जो MongoDB सर्वर 3.4 और इसके बाद के संस्करण में नया है:
मोंगोडीबी सर्वर 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
}
}
});
मोंगोडीबी सर्वर 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
}
}
})