How to use Mongo Bulk Update using its Java Driver? - mongodb

I am using Mongo Bulk Update using its Java Driver 2.13.
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = (DB) mongo.getDB("test");
DBCollection collection = db.getCollection("collection");
BulkWriteOperation builder = collection.initializeOrderedBulkOperation();
builder.find(new BasicDBObject("_id", "1")).update(new BasicDBObject("_id", "1").append("name", "dev"));
I got the following exception:
Caused by: java.lang.IllegalArgumentException: Update document keys must start with $: _id
at com.mongodb.DBCollectionImpl$Run.executeUpdates(DBCollectionImpl.java:769)
at com.mongodb.DBCollectionImpl$Run.execute(DBCollectionImpl.java:734)
at com.mongodb.DBCollectionImpl.executeBulkWriteOperation(DBCollectionImpl.java:149)
at com.mongodb.DBCollection.executeBulkWriteOperation(DBCollection.java:1737)
at com.mongodb.DBCollection.executeBulkWriteOperation(DBCollection.java:1733)
at com.mongodb.BulkWriteOperation.execute(BulkWriteOperation.java:93)

The reason for the error is because when doing updates you must use an update operator. See http://docs.mongodb.org/manual/reference/operator/update/ for a list of update operators.
From your example I gather you are setting the name field to "dev", so you need to use the $set operator like so:
builder.find(new BasicDBObject("_id", "1"))
.update(new BasicDBObject("$set", new BasicDBObject("name", "dev")));

Related

Mongo 3.6.3 java driver aggregate hint - returns undefined field 'hint'

I am trying to pass a hint on an aggregate in MongoDB Java Driver 3.6.3. The aggregate API allows for adding a hint as in:
MongoCollection<Document> coll = database.getCollection("myCollection")
ArrayList<BasicDBObject> docList = new ArrayList<BasicDBObject>();
BasicDBObject hint = new BasicDBObject("$hint","reportjob_customerId_1_siiDocumentAttributes.deleted_1");
MongoCursor<Document> cursor = coll.aggregate(docList).hint(hint).allowDiskUse(batchContext.isAllowDiskUse()).iterator();
I've tried with $hint and hint, but Mongo always returns Command failed with error -1: 'unrecognized field 'hint'
How do I properly send the hint on the aggregate call?
Looks like there is no support to pass the index name directly to hint. So you have pass the index creation document to the hint which you can get by name and use key to get the index document.
MongoCollection<Document> coll = database.getCollection("myCollection");
Bson index = coll.listIndexes().into(new ArrayList<>()).stream().filter(item -> item.getString("name").equals("reportjob_customerId_1_siiDocumentAttributes.deleted_1")).findFirst().get().getString("key");
List<BasicDBObject> docList = new ArrayList<BasicDBObject>();
MongoCursor<Document> cursor = coll.aggregate(docList).hint(index).allowDiskUse(batchContext.isAllowDiskUse()).iterator();
Legacy driver had support for both index name and document.
MongoClient client = new MongoClient();
DB database = client.getDB("myDatabase");
DBCollection coll = database.getCollection("myCollection");
List<BasicDBObject> docList = new ArrayList<BasicDBObject>();
AggregationOptions options = AggregationOptions.builder().allowDiskUse(batchContext.isAllowDiskUse()).build();
DBCursor dbCursor = ((DBCursor) coll.aggregate(docList, options)).hint("reportjob_customerId_1_siiDocumentAttributes.deleted_1");
You can create a jira to have the option to pass index name in the new driver here

how to get all the documents in collection from mongoDB using spring

I was trying to get all the documents from a collection in mongoDB , I am using spring.
MongoTemplate mongoOperation = SpringMongoConfig1.mongoTemplate()
Here in monngoOperation I did not find any method which returns all the docs from a collection .
can anyone help in this ?
If you want to find all the documents of JavaDocumentName(any collection name in java)
List<JavaDocumentName> listRes = mongoOperation.findAll(JavaDocumentName.class);
You can do like this:
//If you don't need connection's configures. i.e. your mongo is in you localhost at 127.0.0.1:27017
MongoClient cliente = new MongoClient(); //to connect into a mongo DB
MongoDatabase mongoDb = client.getDatabase("DBname"); //get database, where DBname is the name of your database
MongoCollection<Document> robosCollection = mongoDb.getCollection("collectionName"); //get the name of the collection that you want
MongoCursor<Document> cursor = robosCollection.find().cursor();//Mongo Cursor interface implementing the iterator protocol
cursor.forEachRemaining(System.out::println); //print all documents in Collection using method reference

DB2 Nosql / MongoDB 'An operator that starts with $ is expected for projectid' error?

I have a list of documents with the structure:
{
from:"string"
to:"string"
payload:{
projectid:10000
}
}
I want to delete all documents with payload.projectid set to 10000 using the java API.
From the command-line I write:
db.notifications.find({"payload":{"projectid":10000}})
Error:
java.lang.RuntimeException: An operator that starts with $ is expected for projectid.
A similar error arises if I delete, whether through cli or programmatically.
This works in normal mongoDB.
How do I delete in db2 nosql?
Java code (for your reference!):
BasicDBObject query = new BasicDBObject();
query.append("to", "username");
query.append("from", "username2");
query.append("payload", new BasicDBObject().append("projectid", 10000));
System.out.println(query); // prints out okay
col.remove(query); //error
You should be using dot notation to reference the sub-document field:
Link
In your case it would be:
db.notifications.find({"payload.projectid":10000})
In Java the find should look something like this:
DBCollection notifications = db.getCollection("notifications")
DBObject subdocumentQuery = new BasicDBObject("payload.projectid", 10000);
DBCursor subdocumentCursor = notifications.find(subdocumentQuery);

getting a pojo from a mongo doc using morphia

Please can someone explain me this code using to create a pojo from a mongo doc? Is it necessary to create a class which contain database fields+getters and setters?
Morphia morphia=....;
MongoClient mongoClient = ............;
DB db = mongoClient.getDB( "contact" );
String contactId=.....;
//load the object from the collection
BasicDBObject idObj=new BasicDBObject ("_id", new ObjectId(contactId));
BasicDBObject obj=(BasicDBObject db.getCollection("personnal").findOne(idObj);
Contact contacy=morphia.fromDBObject(Contact.class,obj);
What value must be afect to contactId?
Why aren't you using Morphia's API if you have it available?
datastore.get(Contact.class, new ObjectId(contactId));

Indexing MongoDB collection in Java

I am creating a collection in MongoDB in the following way and I want to create a 2dsphere index on location field of this collection from Java code. But I am not able to do so.
collection.ensureIndex() method expects a DBObject as a parameter but I cannot pass location to it.
How do I create collection.ensureIndex({"location" : "2dsphere"}) in Java code?
MongoDB allows me to do so in command prompt. But, I want to index it through code written in Java.
BasicDBObject doc = new BasicDBObject("attr1", nextLine[0])
.append("attr2", nextLine[1])
.append("edge-metro-code", nextLine[6])
.append("location", new BasicDBObject("type", "Point")
.append("coordinates",latLong))
.append("attr3", nextLine[9])
.append("attr4", nextLine[10])
ensureIndex() has been deprecated now. You should use createIndex() instead:
MongoClient mongoClient = new MongoClient();
DBCollection test = mongoClient.getDB("testdb").getCollection("test");
test.createIndex(new BasicDBObject("location","2dsphere"));
You should construct a new DBObject that represents your index. See the code bellow:
DBObject index2d = BasicDBObjectBuilder.start("location", "2dsphere").get();
DBCollection collection = new Mongo().getDB("yourdb").getCollection("yourcollection");
collection.ensureIndex(index2d);