N CR7
N CR7

Reputation: 41

Cannot insert into MongoDB using java

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

Answers (3)

Dev
Dev

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

Koustav Ray
Koustav Ray

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:

JavaDriver2.13

or: All Mongo Drivers

Upvotes: 0

Vivek Singh
Vivek Singh

Reputation: 2073

BasicDBObject as subsets of DBObject. Also to save the BasicDBObject we have a call as save method

group.save(documents);

Upvotes: 3

Related Questions