Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

java - How to update value of specific embedded document, inside an array, of a specific document in MongoDB?

I have the following structure in my document:

{
  _id : ObjectId("43jh4j343j4j"), 
  array : [
            { 
              _arrayId : ObjectId("dsd87dsa9d87s9d7"),
              someField : "something",
              someField2 : "something2"
            },
            { 
              _arrayId : ObjectId("sds9a0d9da0d9sa0"),
              someField : "somethingElse",
              someField2 : "somethingElse2"
            }
   ]
 }

I want to update someField and someField2 but only for one of the items in the array, the one that matches _arrayId (e.g. _arrayId : ObjectId("dsd87dsa9d87s9d7"); and only for this document (e.g. _id : ObjectId("43jh4j343j4j") ) and no other.

The arrayIds are not unique to the document that's why I need it to be for a specific document. I could use the $ positional operator if I wanted to update that value within the array for every document it exists in, but that's not what I want.

I am trying to accomplish this in but a command line solution would work as well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is RameshVel's solution translated to :

    DB db = conn.getDB( "yourDB" ); 
    DBCollection coll = db.getCollection( "yourCollection" );

    ObjectId _id = new ObjectId("4e71b07ff391f2b283be2f95");
    ObjectId arrayId = new ObjectId("4e639a918dca838d4575979c");

    BasicDBObject query = new BasicDBObject();
    query.put("_id", _id);
    query.put("array._arrayId", arrayId);

    BasicDBObject data = new BasicDBObject();
    data.put("array.$.someField", "updated");

    BasicDBObject command = new BasicDBObject();
    command.put("$set", data);

    coll.update(query, command);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...