Mandeep Singh
Mandeep Singh

Reputation: 8224

MongoDB : find query with an OR condition with additional column to tag which conidtion the record correspond to

I need to fetch certain records from a table using the following OR query

db.book.find({
    "$or" : [ 
        { "_id': ObjectId("53e49ab8fdc5c42d13965e85")},
        { "topics": { "$in" : ["mysql","MongoDB"] }} 
    ]
})

I need to tag the results in my final output to show where the record came from, i.e. did the record match first condition or the second one. How to do that ?

EDIT:

Posted solution (with help from Phillip)

Upvotes: 1

Views: 49

Answers (2)

Mandeep Singh
Mandeep Singh

Reputation: 8224

db.tbook.aggregate(
{ 
   "$match": {
      "$or": [
        { "_id": ObjectId("53e49ab8fdc5c42d13965e85") },
        {"topics": { "$in" : ["mysql","MongoDB"]}} 
      ]
   } 
},
{ 
   "$project": { 
    "intersect": { 
        $setIntersection: [ "$topics", ["mysql","MongoDB"] ] 
     } 
   } 
},
{ 
   "$project": {
     foundBy: { 
        $cond: {
           if: { $eq : [ "$intersect", [] ] },
           then: "id match",
           else: "topic match"
        }
     }
   }
}
)

Upvotes: 0

Philipp
Philipp

Reputation: 69663

The aggregation framework with the $cond operator could help you here.

The first step of the aggregation would be a $match with the same object you have in your find above. The second step would then be a $project which uses the $cond operator to generate a new field foundBy which gets a different value depending on whether or not the _id of the document matches the one in the query.

$project: {
    // fields from original document you want to retain unchanged:
    any: 1,
    field: 1,
    you: 1,
    need: 1,
    // a new, computed field:
    foundBy: { 
        $cond: {
           if: {$eq: [ "$_id", ObjectId("53e49ab8fdc5c42d13965e85") ] },
           then: "id match",
           else: "topic match"
        }
    }
}

Upvotes: 2

Related Questions