Search code examples
arraysmongodbsubdocumentrestheart

Restheart query for an nested array subdocument


I m working with mongodb and restheart.

In my nosql db i have a unique document with this structure:

{
"_id": "docID",
"users": [
            {
             "userID": "12",                 
             "elements": [
                         {
                          "elementID": "1492446877599",
                          "events": [
                                     {
                                      "event1": "one"
                                     },   
                                     {                                       
                                      "event2": "two",
                                      }
                                     ]
                           }
               },
              {
             "userID": "11",                 
             "elements": [
                         {
                          "elementID": "14924",
                          "events": [
                                     {
                                      "event1": "one"
                                     },   
                                     {                                       
                                      "event2": "two",
                                      }
                                     ]
                           }
               }  

              ]  
}

how can i build an url-query in order to get the user with id 11?

Using mongo shell it should be something like this one:

db.getCollection('collection').find({},{'users':{'$elemMatch':{'userID':'12'}}}).pretty()

I cannot find anything similar on restheart.

Could someone help me?

Using this

http://myHost:port/documents/docID?filter={%27users%27:{%27$elemMatch%27:{%27userID%27:%2712%27}}}

restheart returns me all the documents: userID 11 and 12.


Solution

  • Your request is against a document resource, i.e. the URL is http://myHost:port/documents/docID

    The filter query parameter applies for collection requests, i.e. URLs such as http://myHost:port/documents

    In any case you need to projection (the keys query parameter) to limit the returned properties.

    You should achieve it with the following request (I haven't tried it) using the $elementMatch projection operator:

    http://myHost:port/documents?keys={"users":{"$elemMatch":{"userID":"12"}}}