简体   繁体   中英

Insert array into existing document in mongoDB using Java

I have a document like this:

{
     "_id" : ObjectId("58b1404d002d2b1a481b8ddf"),
     "firstName" : "ABC",
     "lastName" : "XYZ"
}

And I have a list named topics:

List<String> topics = new ArrayList<String>();
topics.add("Business");
topics.add("Technology");
topics.add("Sports");
topics.add("Career");

Now, I want to update my document like this:

{
     "_id" : ObjectId("58b1404d002d2b1a481b8ddf"),
     "firstName" : "ABC",
     "lastName" : "XYZ",
     "readAbout" : ["Business", "Technology", "Sports", "Career"]
}

I tried some ways but ended up with many errors. I am new in this. Please can anyone suggest me how to do this?

You can try something like below. You can adjust the query based on your filter.

Use $push with $each to append each element into an array.

MongoClient client= new MongoClient();
MongoDatabase db = client.getDatabase("dbname");
MongoCollection col = db.getCollection("dbcollection");

List<String> topics = new ArrayList<String>();
topics.add("Business");
topics.add("Technology");
topics.add("Sports");
topics.add("Career");

col.findOneAndUpdate(Filters.eq("_id", new ObjectId("58b1404d002d2b1a481b8ddf")), Updates.pushEach("readAbout", topics));

Use this code, to update single Document Code:

        MongoClient client = new MongoClient("localhost",27017);
        MongoDatabase db = client.getDatabase("count");
        MongoCollection<Document> collection = db.getCollection("test");
        Document query = new Document();
        query.append("firstName" , "ABC");

        List<String> topics = new ArrayList<String>();
        topics.add("Business");
        topics.add("Technology");
        topics.add("Sports");
        topics.add("Career");

    Document setData = new Document();
    setData.append("readAbout", topics);
    Document update = new Document();
    update.append("$set", setData);
    //To update single Document  
    collection.updateOne(query, update);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM