Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB-JSON- How to make a query inside an array?

I have a collection with 20 documents, and each of them has an array.
i want to know how to search for an arrangement that is inside a document
it looks like:

"exist" : 66658,
"warehouse" : [ 
    {
        "stock_I" : "available",
        "prod_st" : "active",
        "last_sale" : "2022-11-23",
        "factura_uv" : 154368244,
        "price" : 8
    }, 
    {
        "stock_II" : "available",
        "prod_st" : "active",
        "last_sale" : "2022-04-18",
        "factura_uv" : 879624124,
        "price" : 8
    }, 
    {
        "stock_III" : "available",
        "prod_st" : "active",
        "last_sale" : "2021-07-05",
        "factura_uv" : 357846988,
        "price" : 8
    }
],

What i want to do is to be able to run a command that shows me only the products that are available in stock_II

my mongo version is 5.0.4

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m grateful for your help

>Solution :

db.collection.aggregate([
  {
    $match: {
      "warehouse.stock_II": "available"
    }
  },
  {
    $set: {
      warehouse: {
        $filter: {
          input: "$warehouse",
          as: "w",
          cond: { $eq: [ "$$w.stock_II", "available" ] }
        }
      }
    }
  }
])

mongoplayground


db.collection.find({
  "warehouse.stock_II": "available"
},
{
  "warehouse.$": 1
})

mongoplayground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading