Need help: $inc peculiar behavior with arrays

Hi All,

I am trying to use $inc operator on some array elements in my documents, but I noticed a peculiar behavior with the query. Can anyone please help me with understand this issue?

I have a document like below:

{
    "nest1" : {
        "uniqueId" : "uniqueId",     
        "isNew" : false,
        "range" : [ 
            {
                "token" : null,
                "message" : null
	    }
          ]
	},
    "body" : {
        "info" : [ 
            {
                "type" : "FacebookUser",
                "totalCalls" : 13252.0,
                
            }, 
            {
                "type" : "TwitterUser",
                "totalCalls":15000.0
            }
        ]
    }
}

I want to increment the value of totalCalls in the info array via update.

This is the command 1 that I tried and it works as expected, the TwitterUser element gets incremented

db.getCollection(“MyCollection”).update({ “nest1.isNew”: false, “nest1.uniqueId”: { $in: [ “uniqueId” ] }, “body.info.type”: “TwitterUser” },{$inc:{“body.info.$.totalCalls”:3}});

But I want to add more conditions to the query, this is the command 2 that I tried, note its query has additional “nest1” fields to be queried for, this increment fails and mongo always updates FacebookUser or first element

db.getCollection(“MyCollection”).update({ “nest1.range.token”:null,“nest1.range.message”:null, “Nest1.isNew”: false, “Nest1.uniqueId”: { $in: [ “uniqueId” ] }, “body.info.type”: “TwitterUser” },{$inc:{“body.info.$.totalCalls”:3}});

Is this some bug? or is this expected behavior?

Can anyone please point out whats wrong here?

Hi @Indian_Ralf,
This may help you.
You can also read this to understand why the $ for your case evaluates to 0.
Good luck,
Rafael,

Thanks Rafael. I am using a version 3.4. Is this possible to do in 3.4?

no, try this instead:

db.getCollection("MyCollection").update({
  "nest1.range": [{"token": null, "message": null}],
  "nest1.isNew": false,
  "nest1.uniqueId": { $in: [ "uniqueId" ] },
  "body.info.type": "TwitterUser"
  },
  {$inc:{"body.info.$.totalCalls":3}}
);

Thanks,
Rafael,

Thanks Rafael, unfortunately this is fetching zero results. I even separated the find query and did a find, it fetched zero results!

Any update or help on this?

Hi @Indian_Ralf,
Try this:

db.getCollection("MyCollection").update({
  "nest1.range": {$elemMatch: {token: null, message:null}},
  "nest1.isNew": false,
  "nest1.uniqueId": {$in :["uniqueId"]},
  "body.info.type": "TwitterUser"
  }, {
    $inc: {
      "body.info.$.totalCalls": 3
    }
  });

Thanks,
Rafael,

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.