Friends
I have a collection with around 20 records of lastAccessed as null and now I want to select a random lastAccessed and update it with $$Now for which I have the below code
db.myCollection.aggregate([
{ $match: { lastAccessed: { $exists: False} }},
{ $sample:{ size: 1 }}
]);
db.myCollection.updateOne(
{ _id: 1 },
{
$set: {
tableName: 'myTable',
lastAccessed: '$$NOW'
}
})
My question is how do I know the id of the randomly selected record to update it correctly ?
CodePudding user response:
For your scenario, you can use $merge
at the end of the aggregation pipeline to perform update by id behaviour.
db.collection.aggregate([
{
$match: {
"lastAccessed": {
$exists: false
}
}
},
{
"$sample": {
"size": 1
}
},
{
$set: {
tableName: "myTable",
lastAccessed: "$$NOW"
}
},
{
"$merge": {
"into": "collection",
"on": "_id",
"whenMatched": "replace"
}
}
])
Here is the Mongo playground for your reference.
CodePudding user response:
If we don't want to use aggregate,
To get Updated Document, can use findOneAndUpdate()
db.collection.findOneAndUpdate(
{ lastAccessed: { $exists: false } },
{ $set: { lastAccessed: "$$NOW" } },
{ returnOriginal: false }
)
Use { returnOriginal: true | false } option for Mongodb 3.6 earlier version,
For MongoDb 3.6 and after 3.6 Version, can use { returnDocument: "after", "before" },
{ new: true | false } option for mongoose