Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I perform atomic updates of fields of a MongoDB document?
    primarykey
    data
    text
    <p>Disclaimer: I'm a noob to Mongo and to databases in general, so if I'm off on terminology or concepts please let me know.</p> <p>For the purposes of this example, I'd like to store the mouse coordinates together within an object nested within a document. That document would look something like:</p> <pre><code>{ "_id" : ObjectId("4f39805d35919a2a7c7aba3e"), "mouseLoc" : { "x" : 10, "y" : 20 } } </code></pre> <p>It seems like <a href="http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations" rel="nofollow">atomic updating, via modifier operations</a>, is the way to go, as I'm only storing values here (retrieving them elsewhere, in other software). However, I can't figure out the query part. How do I access this document in order to set the x and y values?</p> <p>I'm using Java, so I'm currently trying:</p> <pre><code>BasicDBObject mouseLoc = new BasicDBObject(); mouseLoc.put("x", mouseX); mouseLoc.put("y", mouseY); myCollection.update(queryObj, new BasicDBObject("$set", mouseLoc), true, false); </code></pre> <p>However, I don't know how to specify that queryObj to get the document with the mouseLoc key. Alternatively, if there's a smarter way to store information like this, please school me.</p> <p>I can follow along with Mongo shell/JS tips if that's simpler.</p> <p><br/> <strong>UPDATE:</strong><br/> I can query for this document if I give it a static field like 'name'. So, to update this document:</p> <pre><code>{ "_id" : ObjectId("4f39805d35919a2a7c7aba3e"), "name" : "mouseLoc", "mouseLoc" : { "x" : 10, "y" : 20 } } </code></pre> <p>I can use this code:</p> <pre><code>BasicDBObject mouseLoc = new BasicDBObject(); mouseLoc.put("x", mouseX); mouseLoc.put("y", mouseY); BasicDBObject queryObj = new BasicDBObject("name", "mouseLoc"); BasicDBObject updateObj = new BasicDBObject("$set", new BasicDBObject("mouseLoc", mouseLoc)); myCollection.update(queryObj, updateObj, true, false); </code></pre> <p>However, it seems redundant to have to specify that "name" field just to be able to retrieve the document with the "mouseLoc" key. Maybe I'm just misunderstanding database / mongo design?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload