0

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?

2
  • 2
    Plenty of documentation out there to get you started. Commented Jan 18, 2015 at 5:51
  • The _ids are not matching. names become "Names", integers became "ArrayList". Please ensure that question is consistent. Commented Jan 18, 2015 at 7:45

1 Answer 1

4

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

2 Comments

BasicDBObject uses the default _id i.e. ObjectId but how to specify own _id. Please see the question
Answer updated, In your case, you have to explicitly put the "_id"

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.