简体   繁体   中英

How to insert a list of data in mongodb using java

I have a list of integers and list names and I inserted this information in mongodb via console using following code

db.collection.insert({"_id":"integers","data":[1,2,3,4,5]})
db.collection.insert({"_id":"names","data":["A","B","C","D"]})

the query db.collection.find().pretty gave the following result

{ "_id" : "ArrayList", "data" : [ 1, 2, 3, 4, 5, 6 ] }
{
    "_id" : "Names",
    "data" : [
        "A",
        "B",
        "C",
        "D"
    ]
}

How to do it in java?

Just put the list as second arg for BasicDBObject

    ArrayList list = new ArrayList();
    list.add(1);
    list.add(2);
    list.add(3);

    BasicDBObject doc = new BasicDBObject("_id", "ArrayList").append("data", list);

    coll.insert(doc);

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