Bala Karthik
Bala Karthik

Reputation: 1413

MongoDB querying on array of documents

I have the following data in the db

  { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
  { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
  { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
  { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
  { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }

I need to find out the warehouse which has

Upvotes: 0

Views: 40

Answers (2)

bunny9969
bunny9969

Reputation: 21

Try using this find query.

db.warehouse.find(
   {
      $or: [
         {
            item: "paper",
            instock: { $elemMatch: { qty: 15 } }
         },
         {
            item: "postcard",
            instock: { $elemMatch: { qty: 35 } }
         }
      ]
   }
) 

Upvotes: 1

Mayur Vaghasiya
Mayur Vaghasiya

Reputation: 1482

try this code may help you

db.getCollection('warehouses').aggregate([
  {
    $unwind: "$instock"
  },
  {
    $match: {
      $or: [
        {
          $and: [{ 'item': 'paper' }, { 'instock.qty': { $eq: 15 } }]
        },
        {
          $and: [{ 'item': 'postcard' }, { 'instock.qty': { $eq: 35 } }]
        }
      ]
    }
  }
])

Upvotes: 0

Related Questions