Reputation: 1941
I'm using mongo mongo java driver version 2.11.2. I want to insert some few documents into my dbin mongodb and when I try to do it from command line it all works fine. But when I use mongo java driver, it is not working. I'm using BasicDBObject
to populate the document. But collection.insert(BasicDBObject).getN()
gives me 0 always. Nothing is getting inserted into the collection. Am I missing something here?
Adding the code:
mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("db");
DBCollection collection = db.getCollection("collection");
BasicDBObject o = new BasicDBObject();
o.put("key1", "value1");
o.put("key2", "value2");
collection.insert(o);
No update is made in DB after this.
Upvotes: 1
Views: 4520
Reputation: 3383
The 'n' value from the getlasterror of an insert is always zero. (The 'n' value is what the WriteResult.getN() returns.)
See this MongoDB Jira ticket: https://jira.mongodb.org/browse/SERVER-4381. Which has been closed in preference to a new insert, update, remove mechanism: https://jira.mongodb.org/browse/SERVER-9038
Long story short. You are not mad or missing anything. It is a "feature" of MongoDB that will hopefully finally be fixed with the 2.6 release.
Rob.
Edit:
I modified your example slightly to print the saved document. Can you try running this version in your environment?
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;
public class StackOverFlow {
public static void main(String[] args) throws UnknownHostException {
MongoClient mongo = new MongoClient("localhost:27017");
DB db = mongo.getDB("db");
DBCollection collection = db.getCollection("collection");
BasicDBObject o = new BasicDBObject();
o.put("key1", "value1");
o.put("key2", "value2");
collection.insert(WriteConcern.SAFE, o);
for (DBObject doc : collection.find()) {
System.out.println(doc);
}
}
}
On my machine it outputs:
{ "_id" : { "$oid" : "5235f98495302901eb70e7a4"} , "key1" : "value1" , "key2" : "value2"}
Upvotes: 2