arraysjsonmongodbnosqlrobo3t

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

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