简体   繁体   中英

How do I filter by date in mongodb nested arrays?

I need a report. My data is nested. I want to filter by date range. date field string. My Mongo version 3.4.2

I want to filter the 2019 ones in cosDate. that is, my goal is to list the 1.1.2019 - 30.12.2019 minutes. Below is the picture of my related collection

在此处输入图片说明 my example mongo collection https://jsoneditoronline.org/?id=bcac623bb8cd401dbdb62f48bd1c3c68

Using aggregate function with filter we can filter the data according date.

db.demo.aggregate(
      { "$addFields": {
        "costs": 
          {
              "$filter": {
                      "input": "$costs",
                      "as": "sn",
                      "cond": {
                        "$and": [
                          { "$gte": [ "$$sn.costDate", "01/01/2019" ] },
                           { "$lte": [ "$$sn.costDate", "12/01/2019" ] },
                     ]
              },


          }
       } 

    }}
)

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