0

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?

2 Answers 2

3

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.