Frinds I have the following Mongo DB query to select a random record and return the updated record using merge
db.collection.aggregate([
{
$match: {
"lastAccessed": {
$exists: false
}
}
},
{
"$sample": {
"size": 1
}
},
{
$set: {
tableName: "myTable",
lastAccessed: "$$NOW"
}
},
{
"$merge": {
"into": "collection",
"on": "_id",
"whenMatched": "replace"
}
}
])
the return of above query is
[
{
"_id": 3,
"lastAccessed": ISODate("2022-02-16T13:20:38.968Z"),
"tableName": "myTable"
}
]
However I want to tweak above query and return only tableName instead , please let me know how it can be done ?
CodePudding user response:
You can use $project
in your aggregation pipeline to show/hide the fields you want.
db.collection.aggregate([
{
$match: {
"lastAccessed": {
$exists: false
}
}
},
{
"$sample": {
"size": 1
}
},
{
$set: {
tableName: "myTable",
lastAccessed: "$$NOW"
}
},
{
"$merge": {
"into": "collection",
"on": "_id",
"whenMatched": "replace"
}
},
{
$project: {
"tableName": 1,
" _id": 0
}
}
])
will give
[{"tableName": "myTable"}]