Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

couchdb - Mango search in Arrays

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'?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...