Apply a filter on array field of couchDB

432 Views Asked by At

I'm working on Hyperledger fabric. I need a particular value from array not a full document in CouchDB.

Example

{
  "f_id": "1",
  "History": [
    {
      "amount": "1",
      "contactNo": "-",
      "email": "[email protected]"
    },
    {
      "amount": "5",
      "contactNo": "-",
      "email": "[email protected]",

    }
  ],
  "size": "12"
} 

I want only an email :"[email protected]" Object on history array, not a full History array.

mango Query:

{
   "selector": {
      "History": {
         "$elemMatch": {
            "email": "[email protected]"
         }
      }
   }
}

Output:

{
      "f_id": "1",
      "History": [
        {
          "amount": "1",
          "contactNo": "-",
          "email": "[email protected]"
        },
        {
          "amount": "5",
          "contactNo": "-",
          "email": "[email protected]",

        }
      ],
      "size": "12"
    } 

Full History array But needs only the first object of history array.

Can anyone guide me?

Thanks.

1

There are 1 best solutions below

1
hsnkhrmn On

I think it's not possible, because rich queries are for retrieving complete records (key-value pairs) according to given selector.

You may want to reconsider your design. For example if you want to hold an history and query from there, this approach may work out:

  1. GetState of your special key my_record.
  2. If key exists:

    • PutState new value with key my_record.
    • Enrich old value with additional attributes: {"DocType": "my_history", "time": "789546"}. With the help of these new attributes, it will be possible create indexes and search via querying.
    • PutState enriched old value with a new key my_record_<uniqueId>
  3. If key doesn't exists, just put your value with key my_record without any new attributes.

With this approach my_record key will always hold latest value. You can query history with any attributes with/out pagination by using indexes (or not, based on your performance concerns).

This approach will also be less space consuming approach. Because if you accumulate history on single key, existing history will be copied to next version every time which means your every entry will consume previous_size + delta, instead of just delta.