Reputation: 310
How to add a particular value for all records in the collection using aggregation :
Have a collection with data :
[
{
_id: "bmasndvhjbcw",
name: "lucas",
occupation: "scientist",
present_working:true,
age: 55,
location: "texas",
date:2019-11-25T01:00:00.000+00:00
},
{
_id: "bmasndvhjbcx",
name: "mark",
occupation: "scientist",
age: 45,
location: "texas",
date:2019-11-25T01:00:00.000+00:00
},
{
_id: "bmasndvhjbcq",
name: "cooper",
occupation: "physicist",
age: 69,
location: "texas",
date:2019-11-25T01:00:00.000+00:00
}
]
if date column exists for any of the records present_working:true
should be added in the collection for the records
expected output:
[
{
_id: "bmasndvhjbcw",
name: "lucas",
occupation: "scientist",
present_working:true,
age: 55,
location: "texas",
date:2019-11-25T01:00:00.000+00:00
},
{
_id: "bmasndvhjbcx",
name: "mark",
occupation: "scientist",
present_working:true,
age: 45,
location: "texas",
date:2019-11-25T01:00:00.000+00:00
},
{
_id: "bmasndvhjbcq",
name: "cooper",
occupation: "physicist",
present_working:true,
age: 69,
location: "texas",
date:2019-11-25T01:00:00.000+00:00
}
]
Upvotes: 1
Views: 50
Reputation: 17925
So if you wanted to return conditionally add a field based upon existence of other field in aggregation while reading data from database then try below query :
/** If `date` exists then it will add the field & assign value to true else `$$REMOVE` will help to not add the field at all,
* Additionally if you're ok to add this new field for docs where `date : null` then replace `$gt` with `$gte` */
db.collection.aggregate([
{
$addFields: {
present_working: { $cond: [ { "$gt": [ "$date", null ] }, true, "$$REMOVE" ] }
}
}
])
Test : mongoplayground
Ref : aggregation-pipeline
Upvotes: 1
Reputation: 2637
There is no need to use aggregation for this.
You can do it simply this way:
collection.updateMany({
date: {
$exists: true
}
}, {
$set: {
present_working: true
}
})
If you want to do it with the aggregation framework:
collection.aggregate(
[
{
"$match" : {
"date" : {
$exists: true
}
}
},
{
"$addFields" : {
"present_working" : true
}
}
]
)
Upvotes: 2