1

There is a document like this:

{ 
    "_id" : ObjectId("591ec6ca277b295fa98a772b"), 
    "userId" : 10, 
    "appPrefs" : [ 
        { 
            "type" : "navi", 
            "elements" : [ 
                { 
                    "name" : "apple", 
                    "value" : "", 
                    "updateTime" : NumberLong(1222222222)                        
                }, 
                { 
                    "name" : "banana", 
                    "value" : "", 
                    "updateTime" : NumberLong(1222222222)                        
                } 
            ] 
        } 
    ] 
}

You may find that elements is a collection and embedded in another collection appPrefs.

I want to update the updateTime if it's less than specific update time (for example 1300000000) and the userId = 10 &&type = navi && elements.name = apple. Firstly I'm trying to match the element and write a query, but no item returned.

db.cname.find({"userId" : 10, "appPrefs":{$elemMatch: {type : "navi", "elements": {$elemMatch: {name : "apple"}}}}})

But no item returned. Could anyone help to check why it happened?

Thanks in advance.


Update the query as @Samip Suwal said.


Junjie
  • 1,145
  • 3
  • 21
  • 37

2 Answers2

2

well in the query that you have provided I see a typo for the field "elements". You have "elemments" instead of "elements" So changing

db.cname.find({"userId" : 10, "appPrefs":{$elemMatch: {type : "navi", "elemments": {$elemMatch: {name : "apple"}}}}})

to

db.cname.find({"userId" : 10, "appPrefs":{$elemMatch: {type : "navi", "elements": {$elemMatch: {name : "apple"}}}}})

should return you a match.

For the update part. I don't think it is possible two update an element inside multiple nested array in mongodb at the moment. Here is a jira request, jira-831, request that addresses this.

Also in cases where there are multiple elements that match the query, I believe mongodb doesn't support update on all matching items in an array either. Here is a jira request, jira-1243, that addresses this.

Samip Suwal
  • 1,253
  • 11
  • 17
1

You can not do that since this is a current limitation of Mongodb. In here you are trying to update an element in nested array.When we need to update an element inside an array, $ is used to keep the position. But it support only one level. In here there is two levels.You can refer this for more details. But You have two options to do that.

  1. You can split this documents into two collections and use references.
  2. You can search the document (this can be done) and in java you can manipulate the document in java, and save back.
Community
  • 1
  • 1
Lakmal Vithanage
  • 2,767
  • 7
  • 42
  • 58