Change Value of Nested Object - MongoDB Java

I'm making a MongoDB statistic system using the Java driver, and I am wondering if it is possible (and how) to change the value of a key nested inside many objects. Here is how my database is formatted:

  location : “chicago”,
  stats : [
      "employee" : "rob",
      "stat1" : 1,
      "stat2" : 3,
      "stat3" : 2
      "employee" : "krista",
      "stat1" : 1,
      "stat2" : 3,
      "stat3" : 2

So, for example, how could I change Rob's "stat2" to another value? I am new to JSON and the MongoDB Java driver. Any help is appreciated!


You need to use the positional $ operator and $set in order to update what you want.

    { _id: <docId>, "stats.employee": "rob" }, 
    { "$set": { "stats.$.stat2": <value> } }

So you match your document and the required element of the array. The update side uses that array index to know in which element to update. The $set operator only updates the specified field.

In Java, Build with BasicDBObject.

BasicDBObject query = new BasicDBObject("_id", id);
query.append( new BasicDBObject("stats.employee", "rob") );

BasicDBObject update = new BasicDBObject("$set",
    new BasicDBObject("stats.$.stat2", value));


Need Your Help

Create SQL Server CREATE ASSEMBLY script automatically

c# sql-server sql-server-2008 sql-server-2005

When I use SSMS to create an assembly dll, it generates a script like this :

Why main() is declared public and static in java

java static main public

Why is the main declared as public and static?