K JH
K JH

Reputation: 29

How can I find matching elements in an array using CouchDB's Mango selector?

How can I find selected only elements included value during array elements using CouchDB's Mango API?

I tried $elemMatch, but I didn't get the result I wanted

Document

    {
      "id": "id1",
      "user_info": [
        {
          "name": "kk",
          "age": "17",
        },
        {
          "name": "jj",
          "age": "21",
        },
        {
          "name": "kk",
          "age": "19",
        }
      ],
    }

my sql

{
        "selector": {
           "id": "id",
           "user_info": {
              "$elemMatch": {
                 "name": "kk"
              }
           }
        }
     }

now result :

    {
      "id": "id1",
      "user_info": [
        {
          "name": "kk",
          "age": "17",
        },
        {
          "name": "jj",
          "age": "21",
        },
        {
          "name": "kk",
          "age": "19",
        }
      ],
    }

But I want this result

    {
      "id": "id1",
      "user_info": [
        {
          "name": "kk",
          "age": "17",
        },
        {
          "name": "kk",
          "age": "19",
        }
      ],
    }

How can i get data I wanted?

I use CouchDB

I access CouchDB by go language

Upvotes: 1

Views: 351

Answers (1)

Glynn Bird
Glynn Bird

Reputation: 5637

If you perform a query of this form:

{
   "selector": {
      "user_info": {
         "$elemMatch": {
            "name": "kk"
         }
      }
   }
}

You are asking the database for documents that have a user_info array which contains an object, one of whose's attributes is name with a value of kk.

This correctly returns the the whole documents that match this criteria.

If you want to extract a sub-set of the documents, you'll have to do that transformation in your client-side code once the database has returned the matching documents.

Upvotes: 3

Related Questions