简体   繁体   中英

Save list of objects in mongodb

I have list of cars { car1, car2, car3 } and each car has at least two or more fields. The list is converted to BasicDBList. Example here

DBObject saveObject = new BasicDBObject().append("$push", dbBasicListOfCars);
collection.(car).save(saveObject);

It fails to save the list in its own collection and complains about the field cannot start with '$' sign.

How can I push the whole list in a collection? Or do I have to save individual car in collection?

new BasicDBObject().append("$push", dbBasicListOfCars);

In the above statement, you are trying to insert a key-value pair in DBObject with key as "$push" and value as dbBasicListOfCars . MongoDB doesnt allow key to have a '$' hence it is failing.

However, the way you are trying to save is also wrong.

What you need is com.mongodb.BasicDBList, which is a utility class to allow array DBObjects to be created. BasicDBList only supports numeric keys. Passing strings that cannot be converted to ints will cause an IllegalArgumentException.

 BasicDBList list = new BasicDBList();
 list.put("1", "bar"); // ok
 list.put("1E1", "bar"); // throws exception

refer : http://api.mongodb.org/java/current/com/mongodb/BasicDBList.html

Note: MongoDB will also create arrays from java.util.Lists.

DBObject obj = new BasicDBList();
 obj.put( "0", value1 );
 obj.put( "4", value2 );
 obj.put( 2, value3 );

This simulates the array [ value1, null, value3, null, value2 ] by creating the DBObject { "0" : value1, "1" : null, "2" : value3, "3" : null, "4" : value2 }.

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