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
305 views
in Technique[技术] by (71.8m points)

mongodb - Java MongoClient to add a new embedded document

I have a below data type in mongodb

{
    "_id" : ObjectId("60007b3abc54b5305e9f5601"),
    "description" : "Mens",
    "name" : "Men"
}

Since the above data is already an existing data, Now using the MongoClient I want to insert the new embedded document based on the _id as below

{
    "_id" : ObjectId("60007b3abc54b5305e9f5601"),
    "description" : "Mens",
    "name" : "Men",
    "subCategory" : [{
        "name" : "This is name update",
        "description" : "This is update"
    }]
}

Once, the array has been inserted, Again I have the requirement to add another item to the array, something like below

{
    "_id" : ObjectId("60007b3abc54b5305e9f5601"),
    "description" : "Mens",
    "name" : "Men",
    "subCategory" : [{
        "name" : "This is name update",
        "description" : "This is update"
    },
{
        "name" : "This is name update",
        "description" : "This is update"
    }]
}
question from:https://stackoverflow.com/questions/65860018/java-mongoclient-to-add-a-new-embedded-document

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

1 Reply

0 votes
by (71.8m points)

Code to update :

import static com.mongodb.client.model.Filters.eq;

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("some_db_name");
MongoCollection<Document> collection = database.getCollection("some_database");
Document document = collection.find(eq("_id", new ObjectId("60007b3abc54b5305e9f5601")))
                              .first();

Object object = document.get("subCategory");

List<Document> documents = new ArrayList<>();

if(object != null) {
  documents = (List<Document>) object;
}

documents.add(new Document("name", "This is name update")
              .append("description", "This is update")); 

document.append("subCategory", documents);

collection.updateOne(eq("_id", new ObjectId("60007b3abc54b5305e9f5601")), 
         new Document("$set", new Document("subCategory", documents)));

 

Read docs : https://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/


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

...