Mango search in Arrays

自闭症网瘾萝莉.ら 提交于 2019-11-27 04:43:34

问题


My document has a structure like this:

{
  "Calibration": {
    "Presettings": {
      "Date": [
        {
          "Value": "2016-09-02 10:11",
          "Type": "generated"
        },
        {
          "Value": "2016-09-05",
          "Type": "schedule",
          "Duration": "5"
        }
      ]
    }
  }
}

How must I define the selector part of a query object to get all documents with dates (Value) less or equal to a given date and with Type=='generated'?


回答1:


First, you need to create your index. I suggest that you create an index on the Calibration.Presettings.Date field.

You can use the following JSON object to create it:

{
  "index": {
    "fields": [
      "_id",
      "Calibration.Presettings.Date.[].Type"
    ]
  },
  "type": "json"
}

So the selector would be like this :

{
  "selector": {
    "Calibration.Presettings.Date": {
      "$elemMatch": {
        "$and": [
          {
            "Type": "generated"
          },
          {
            "Value": {
              "$gte": "2016-09-01"
            }
          }
        ]
      }
    }
  }
}

We execute the query on the field Calibration.Pressettings.Date which is an Array. Since it's an array, we have to use the $elemMatch operator.

Then, we have a $and condition for the Value and the Type.

The Type of the Date has to be generated. With can either use the $eq operator or simply use this simple syntax: {"field":"value"}.

Finally, the Date`s Value must be greater or equal to X date. We can use the $gte operator.



来源:https://stackoverflow.com/questions/43892556/mango-search-in-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!