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

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

Related

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

How to fetch mongo db data and pass in jmeter request

I have one post call that response is like this.
{
"status":0,
"message":"Prescription Created",
"jsonResponse":{},
"cid":"C5975K",
"pid":"Rx5975K-175A",
"prescriptionSource":"GO_RX_CTO",
"imageStatus":[]
}
By taking this pid , I have to do the query for the one more record. For example:
db.order.find({"pid":"Rx5975K-175A"})
and the result of this query should pass in one more jmeter request.
I have used MongoDB Script (DEPRECATED) .. But this wont work as its deprecated ..
Tried with JSR223 Sampler, but its not working in new jmeter 3.2
import com.mongodb.*
import com.mongodb.BasicDBObject
MongoCredential coreCredential = MongoCredential.createCredential("${mongodb_user}", "${mongodb_database}", "${mongodb_password}".toCharArray());
MongoClient coreMongoClient = new MongoClient(new ServerAddress("${mongodb_server}", 13017), Arrays.asList(coreCredential));
DB coreDB = coreMongoClient.getDB("${mongodb_database}");
DBCollection coll = coreDB.getCollection("order");
coll.find();
You have to find your result based on "pid" and you are nowhere passing it. After finding you collection you need to create a query and searching using that query.
import com.mongodb.*
import com.mongodb.BasicDBObject
MongoCredential coreCredential = MongoCredential.createCredential("${mongodb_user}", "${mongodb_database}", "${mongodb_password}".toCharArray());
MongoClient coreMongoClient = new MongoClient(new ServerAddress("${mongodb_server}", 13017), Arrays.asList(coreCredential));
DB coreDB = coreMongoClient.getDB("${mongodb_database}");
DBCollection coll = coreDB.getCollection("order");
BasicDBObject query = new BasicDBObject();
query.put("pid", "Rx5975K-175A");
DBObject getData= coll.findOne(query);
and this will give you the desire result

In mongodb version 3 using java api how do we give a hint while querying

In mongodb version 3 using java api how do we give a hint while querying
The query result is FindIterable which has MongoCursor.
How should I give a hint to use a particular index.
With older versions there is DBCursor which have API's for hint.
modifiers should be used:
BasicDBObject index = new BasicDBObject("num", 1);
BasicDBObject hint = new BasicDBObject("$hint", index);
FindIterable<Document> iterable = collection.find().modifiers(hint);
You need to use FindIterable.modifiers method to specify $hint:
private static void testHint(MongoDatabase db) {
MongoCollection<Document> col = db.getCollection("Stores");
FindIterable<Document> iterable = col.find(new Document("store","storenumbervalue"));
iterable.modifiers(new Document("$hint","index_name"));
MongoCursor curs = iterable.iterator();
while(curs.hasNext()){
System.out.println(curs.next());
}
}
index_name - actual index name in mongo.

How to use Mongo Bulk Update using its Java Driver?

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")));

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);