Reputation: 41
I am new to MongoDb. I am trying to insert the data in MongoDb using java. Everything works fine but when i try to use insert()
function to insert the data error is shown. It says change type of documents to DBObject[]
.
Database.java
package database;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
public class Database
{
public static void main(String args[])
{
MongoClient mongo= new MongoClient("localhost",80);
DB db = mongo.getDB("Collection");
DBCollection group=db.getCollection("Group");
BasicDBObject documents= new BasicDBObject();
documents.put("saf", "ad");
group.insert(documents);//error is shown here
}
}
Upvotes: 0
Views: 1255
Reputation: 13753
You are using .insert()
on DBCollection.
public WriteResult insert(DBObject... arr)
throws MongoException
Saves document(s) to the database. if doc doesn't have an _id, one will be added you can get the _id that was added from doc after the insert
Parameters:
arr - array of documents to save
Throws:
MongoException
Check JavaDoc for insert. This is expecting an array of DBObject.
That's why the error:
change type of documents to DBObject[]
As @Vivek mentioned, you can use .save()
method:
public final WriteResult save(DBObject jo)
Saves an object to this collection.
Parameters:
jo - the DBObject to save will add _id field to jo if needed
Check Javadoc for save.
Upvotes: 0
Reputation: 1142
Your Code is correct and runs as is. Just update the mongo-java driver to version 2.13.0 from your existing one. Download link:
Upvotes: 0
Reputation: 2073
BasicDBObject as subsets of DBObject. Also to save the BasicDBObject we have a call as save method
group.save(documents);
Upvotes: 3