Reputation: 494
I need a query in MongoDB where I turn a list into True or False depending on whether a value exists in the list or not.
Here's a summarized view of the schema.
{'_id': ObjectId('604edf91571e7ab19cc2c238'),
'timestamp': 1616164767.773929,
'name': 'some name',
'metric1': 1,
'metric2': 2,
'metric3': 3,
'tags': ['tag1', 'tag2', 'tag3', 'tag that matters']}
Is there a way to change the tags key to a value of True or False if a 'tag that matters'
is in the list? I don't want to exclude records that don't have the tag, I just want those records to have a value of False for the tags key.
Upvotes: 0
Views: 103
Reputation: 4452
Try this query:
db.collectionName.aggregate([
{
"$addFields": {
"tags": {
$map: {
input: "$tags",
as: "tag",
in: {
$eq: ['$$tag', 'tag that matters']
}
}
}
}
}
]);
Output:
{
"_id" : ObjectId("604edf91571e7ab19cc2c238"),
"timestamp" : 1616164767.773929,
"name" : "some name",
"metric1" : 1,
"metric2" : 2,
"metric3" : 3,
"tags" : [
false,
false,
false,
true
]
}
Upvotes: 1
Reputation: 494
need to use an $in
operator in the project stage.
{
"$project": {
"_id": "$_id",
"timestamp": "$timestamp",
"name": "$name",
"metric1": "$metric1",
"metric2": "$metric2",
"metric3": "$metric3",
"tags": {
"$in": ["tag that matters", "$tags"]
}
}
}
Upvotes: 0