Access element in mongo array in java

2020-07-27 03:40发布

问题:

Say I have the following mongo object in a database:

{
    "_id" : ObjectId("4f904ebb5bebd4375b759c90"),
    "findme" : "someValue",
    "array" : [
        {
            "id" : "1234"
            "Y" : "0"
        },
        {
            "id" : "3456"
            "Y" : "0"
        },
        {
            "id" : "5678"
            "Z" : "0"
        }
    ]
}

I know that i can change the array contents with the following dot notation accessors in java...

BasicDBObject change = new BasicDBObject("findme", "someValue");   
BasicDBObject setDoc = new BasicDBObject();                 
setDoc.append("array.0.Y", "0");                                        
setDoc.append("array.1.Y", "0");                                      
setDoc.append("array.2.Z", "0");                                          
BasicDBObject account = new BasicDBObject("$set", setDoc);
coll.update(change, account);

But how would I change the value of "3456"'s "Y" if I only knew that the id was "3456" and not that it was at index 1 in "array"? I would really like to accomplish this entirely within the creation of these query objects and the update method... In other words I'd rather not pull the whole object out and iterate through the "array" to find out it's position.

Thanks!

Edit: Multiple array elements can have the field "Y" as shown in the edited code. I only want to edit a specific element's "Y" field.

回答1:

To do this using the Java driver, you can do the following:

DBObject queryForElem = new BasicDBObject("array", new BasicDBObject("$elemMatch", new BasicDBObject("id", "3456")));
DBObject updateMatchingElem = new BasicDBObject("$set", new BasicDBObject("array.$.Y", "1"));
coll.update(queryForElem, updateMatchingElem);

Given that that's a bit unwieldy, you can use the QueryBuilder instead, which gives you a little more readability:

DBObject queryForElem = QueryBuilder.start("array").elemMatch(new BasicDBObject("id", "3456")).get();
DBObject updateMatchingElem = new BasicDBObject("$set", new BasicDBObject("array.$.Y", "1"));
coll.update(queryForElem, updateMatchingElem);


回答2:

db.collection.update({array : {$elemMatch : {id : "3456"}}}, {$set : { 'array.$.Y' : '1' }})


标签: java mongodb