0

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?

3
  • I believe it's complaining about your key in that append and saying that that should not start with a $. Commented Dec 8, 2012 at 1:59
  • I know that. So how should I resolve the problem :) Commented Dec 8, 2012 at 2:12
  • There is a difference between save and update methods in MongoDB. $push operation is for update method. Commented Dec 8, 2012 at 10:52

1 Answer 1

1
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 }.

Sign up to request clarification or add additional context in comments.

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.