简体   繁体   中英

mongodb How to find only part of an array

I want to get an array returned using the "find" function in the data below The contents of the array are as follows.

{qty:15 warehouse:C},
{qty:20 warehouse:C},
{qty:25 warehouse:C}

I don't want "first element"
I want to return an array where gty is greater than 20.
How can I do this?

Receive document returned from mongodb
Do I have to pull it out directly with a loop?
Is there a way to get it out with a query?


{
    _id: ObjectId('60d0b364737d829c870b7571'),
    item: 'journal',
    instock: [
        {
            warehouse: 'A',
            qty: 5
        },
        {
            warehouse: 'C',
            qty: 15
        },
        {
            warehouse: 'C',
            qty: 20
        },
        {
            warehouse: 'C',
            qty: 25
        }
    ]
}

You can use Aggregation Pipeline:

  • $match to match all documents that you want to query
  • $project to select what fields you want to return
  • $filter to filter instock array by some condition
db.collection.aggregate([
  {
    "$match": {
      "_id": "id_1"
    }
  },
  {
    "$project": {
      "item": 1,
      "instock": {
        "$filter": {
          "input": "$instock",
          "cond": {
            "$gt": [
              "$$this.qty",
              20
            ]
          }
        }
      }
    }
  }
])

Here is a working example: https://mongoplayground.net/p/-RPGEriBxui

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM