3

Query:

Select * from table1 where f1 = "val1" OR f1 = "val2"

I need to convert this query to MongoDB query but using aggregation not find.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
user1735921
  • 1,359
  • 1
  • 21
  • 46

2 Answers2

2

Have a look at $match and $in or $or
Your query could look like this

db.table1.aggregate( [
  { $match: { f1: { $in: ['val1', 'val2'] } } }
] );
DAXaholic
  • 33,312
  • 6
  • 76
  • 74
2

You don't necessarily need the aggregation framework for this, a simple find() query with the $in or $or operator will do just fine:

db.collection.find({
    "f1": { "$in": ["val1", "val2"] }
})

Using the $or operator:

db.collection.find({
    "$or": [
        { "f1": "val1" },
        { "f1": "val2" }
    ]
})

which is just syntantic sugar for the above $in


For an aggregation pipeline approach, you can run the following pipeline which uses the $match operator to query:

db.collection.aggregate([
    { "$match": { "f1": { "$in": ["val1", "val2"] } } }
])

or with the $or operator

db.collection.aggregate([
    { 
        "$match": { 
           "$or": [
               { "f1": "val1" }, 
               { "f1": "val2" }
           ] 
        } 
    } 
])

From the docs $or vs $in, it's recommended

When using $or with <expressions> that are equality checks for the value of the same field, use the $in operator instead of the $or operator.

chridam
  • 100,957
  • 23
  • 236
  • 235