B00100100
B00100100

Reputation: 33

MongoDB Query Multiple Specific Documents

I would like to make a single query to my backend database to retrieve a list of results. These results will have a unique "product_id" and they will also have a "variant_id". Items may share product IDs but must have unique variant IDs. For Example

{
  product_id:"123",
  variant_id:"000"
}

{
  product_id:"123",
  variant_id:"111"
}

{
  product_id:"987",
  variant_id:"000"
}

Is it possible to write a single query that would only find

the Product with an ID of "123" and variant "000"

And the product with ID "987" and variant "000"

{
  product_id:"123",
  variant_id:"111"
}

{
  product_id:"987",
  variant_id:"000"
}

I have search this issue and only found answers related to the $in operator. but I don't think that will allow me to do what I need here? could someone point me in the right direction or let me know if this is even possible. I'm trying to avoid making individual request the the database for each item.

Upvotes: 0

Views: 93

Answers (1)

R2D2
R2D2

Reputation: 10737

Simple $or can do the job:

db.collection.find({
$or: [
 {
  "product_id": "123",
  "variant_id": "000"
 },
 {
  "product_id": "987",
  "variant_id": "000"
 }
]
})

playground

Upvotes: 1

Related Questions