Home > Enterprise >  Getting only certain data from list in document in Mongo
Getting only certain data from list in document in Mongo

Time:12-01

[
  {
    "_id": "",
    "at": IsoDate(2022-11-19 10:00:00),
    "areaId": 3,
    "data": [
      {
        "label": 1,
        "name": "a",
        "sec": 34,
        "x": 10.3,
        "y": 23.3
      },
      {
        "label": 1,
        "name": "a",
        "sec": 36,
        "x": 10.3,
        "y": 23.3
      },
      {
        "label": 1,
        "name": "c",
        "sec": 37,
        "x": 10.3,
        "y": 23.3
      }
      ]
  },
  {
    "_id": "",
    "at": IsoDate(2022-11-19 10:01:00),
    "areaId": 3,
    "data": [
      {
        "name": "a",
        "label": 1,
        "sec": 10,
        "x": 10.3,
        "y": 23.3
      },
      {
        "label": 2,
        "name": "b",
        "sec": 12,
        "x": 10.3,
        "y": 23.3
      }
      ]
  }
  ]

I have a mongo bson data as above. This data holds areaId based login information in 1-minute packets. Getting all label=1 data in the date range given here. I want to get it in the most performance way since the data size is very large. This query can be in the same data format and in the data list, only the ones with a label of 1 can be returned. Do you think it's a good idea?

How can I write a query for this? Could it be a bsondocument query too, since I'm extracting the query in c#?

CodePudding user response:

Try this one:

db.collection.aggregate([
   {
      $match: {
         at: {
            $gt: ISODate('2022-11-01'), $lt: ISODate('2022-12-01')
         }
      }
   },
   { $set: { data: { $filter: { input: "$data", cond: { $eq: ["$$this.label", 1] } } } } }
])

Mongo Playground

  • Related