How to use multiple condition in mongodb query?

Member

by domenico , in category: MySQL , 3 months ago

How to use multiple condition in mongodb query?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 3 months ago

@domenico 

In MongoDB, you can use multiple conditions in a query by using the $and, $or, and $nor operators.


Here's an example of how to use multiple conditions in MongoDB query:

1
2
3
4
5
6
db.collectionName.find({
  $and: [
    { field1: value1 },
    { field2: value2 }
  ]
})


In this example, the query will look for documents where field1 is equal to value1 and field2 is equal to value2.


You can also use the $or operator to query for documents that meet at least one of the conditions:

1
2
3
4
5
6
db.collectionName.find({
  $or: [
    { field1: value1 },
    { field2: value2 }
  ]
})


In this case, the query will return documents where either field1 is equal to value1 or field2 is equal to value2.


You can also negate conditions using the $nor operator:

1
2
3
4
5
6
db.collectionName.find({
  $nor: [
    { field1: value1 },
    { field2: value2 }
  ]
})


This query will return documents where neither field1 is equal to value1 nor field2 is equal to value2.


You can combine these operators to create complex queries with multiple conditions. Just make sure to properly nest your conditions within the respective operator.