mongo group with match query does not work with java - mongodb

I have below query working in robo 3T console.
db.metrics.aggregate([
{'$match':{'status':'SUCCESS'}},
{'$group':{ _id:'$bapiName',count:{$sum:1}}}
])
But when I execute it with java,
MongoCollection collection =db.getCollection();
List<Bson> pipeLine = new ArrayList<Bson>();
pipeLine.add(Document.parse("{'$match':{'status':'SUCCESS'}}"));
pipeLine.add(Document.parse("{'$group' : {_id: {bapiName:'$bapiName',status:'$status'}, count:{$sum:1}}}"));
Iterator iterator = collection.aggregate(query.getPipeline()).iterator();
while( iterator.hasNext()) {
Object object = iterator.next();
resultList.add((Document)object);
System.out.println(" class "+object.getClass()+" data "+object);
}
I am not getting the results. Iterator is empty. Any changes need to be made in java to get it working?

Related

mongodb 3.2 java driver aggregation whith match on lookup

I wonder how to perform the aggregation $match on a $lookup collection with the java driver for mongodb 3.2. Here is the structure of the two collections i am working on :
coll_one:{
_id : ObjectId("hex_string"),
foreign_id : ObjectId("hex_string") **the id of coll_two**}
coll_two:{
_id : ObjectId("hex_string"),
actif : true,
closed : false }
The lookup on the two ids (coll_one.foreign_id & coll_two._id) seems to work fine. But when i specify a match on coll_two.actif = true, it returns an empty result.
This is the Java code i'am using :
Bson lookup = new Document("$lookup",
new Document("from", "coll_two" )
.append("localField", "foreign_id")
.append("foreignField", "_id")
.append("as", "look_coll"));
List<Bson> filters = new ArrayList<Bson>();
filters.add(lookup);
//here is the MATCH
filters.add(match(eq("look_coll.actif",true)));
DB().getCollection("coll_one").aggregate(filters);
Evrything works fine whene i remove the match section. I have tried so many combination of possibilities with no success at all !!!
Can any body tells me if this is possible ????
Add your $match request to a Document instance :
Bson match = new Document("$match",
new Document("look_coll.actif", true));
filters.add(match);
Here is a full example :
MongoClient mongoClient = new MongoClient("localhost");
MongoDatabase db = mongoClient.getDatabase("mydb");
Bson lookup = new Document("$lookup",
new Document("from", "coll_two")
.append("localField", "foreign_id")
.append("foreignField", "_id")
.append("as", "look_coll"));
Bson match = new Document("$match",
new Document("look_coll.actif", true));
List<Bson> filters = new ArrayList<>();
filters.add(lookup);
filters.add(match);
AggregateIterable<Document> it = db.getCollection("coll_one").aggregate(filters);
for (Document row : it) {
System.out.println(row.toJson());
}

When does MongoDB Fetch results in java driver

MongoClient mc=new MongoClient();
MongoDatabase mdb=mc.getDatabase("testdb");
MongoCollection mcol=mdb.getCollection("testcol");
FindIterable<Document> fi=mcol.find();
MongoCursor<Document> mcur=fi.iterator();
MongoCursor<Document> mcur2=fi.iterator();
will mcur and mcur2 have same results all the time as they are reference of FindIterable fi.
In which step of the above code mongodb will get the results Inside mongoCursor or FindIterable step?
mcol.find() is the point where the results are obtained, the .find() will pull all documents from the collection "testcol".
You don't necessarily need to use a FindIterable object an ordinary List<BasicDBObject> does work.
then you can iterate through using:
for(DBObject obj : objList) {
//perform operations
String name = (String) obj.get("nameOfField");
}
hope this helps.

how to call count operation after find with mongodb java driver

I am using MongoDB 3.0. suppose there is a set of documents named photos, its structure is
{"_id" : 1, photographer: "jack"}
with database.getCollection("photos"), Mongodb will return a MongoCollection object, on which I have the method count() to get the number documents returned.
However, when I make queries with specific conditions. For example find documents with id smaller than 100 :
photosCollections.find(Document.parse("{_id : {$lt : 100}}"))
Above find method will always return a cursor which doesn't provide a count() function. So how can I know how many documents returned ? I know on command line, I can use
db.photos.find({_id : {$lt : 100}}).count()
Of course, I can go through the iterator and count the number of documents myself. However I find it really clumsy. I am wondering does MongoDB java driver provides such functionality to count the number of documents returned by the find() method ? If not, what is the reason behind the decision ?
As you said the MongoCollection has the count() method that will return the number of documents in the collection, but it has also a count(Bson filter) that will return the number of documents in the collection according to the given options.
So you can just use:
long count = photosCollections.count(Document.parse("{_id : {$lt : 100}}"))
or maybe clearer:
Document query = new Document("_id", new Document("$lt", 100));
long count = photosCollections.count(query);
ref: http://api.mongodb.com/java/3.3/com/mongodb/client/MongoCollection.html#count-org.bson.conversions.Bson-
In MongoDB 3.4 you can only use the Iterator of FindIterable to get the count of the documents returned by a filter. e.g.
FindIterable findIterable =
mongoCollection.find(Filters.eq("EVENT_TYPE", "Sport"));
Iterator iterator = findIterable.iterator();
int count = 0;
while (iterator.hasNext()) {
iterator.next();
count++;
}
System.out.println(">>>>> count = " + count);
I had a similar problem. I am using MongoCollection instead of DBCollection, as it is what it is used in MongoDG 3.2 guide. MongoCollection hasn't got count() method, so I think the only option is to use the iterator to count them.
In my case I only needed to know if any document has been returned, I am using this:
if(result.first() != null)
Bson bson = Filters.eq("type", "work");
List<Document> list = collection.find(bson).into(new ArrayList<>());
System.out.println(list.size());
into(A) (A is collection type) method iterates over all the documents and adds each to the given target. Then we can get the count of the returned documents.
The API docs clearly state that DBCursor Object provides a count method:
MongoClient client = new MongoClient(MONGOHOST,MONGOPORT);
DBCollection coll = client.getDB(DBNAME).getCollection(COLLECTION);
DBObject query = new Querybuilder().start()
.put("_id").lessThan(100).get();
DBCursor result = coll.find(query);
System.out.println("Number of pictures found: " + result.count() );

Grails Mongo Low Level API

What would be the equivalent of this line in groovy code when using the Mongo low level API?
db.countrycodes.findOne({"Country":"Antarctica"})
This line successfully finds the appropriate record for me in the Mongo shell but I tried many variations of it in my controller method and I keep getting NULL. Heres is my current attempt which is failing:
MongoClient mongoClient = new MongoClient("localhost", 27017)
DB db = mongoClient.getDB("twcdb");
DBCollection coll = db.getCollection('countrycodes')
println coll.find("Country":"Antarctica")
I know my collection and db is non NULL because when I do find() I do get a valid cursor back through which I can print the first record in collection. Here is the record I am trying to find:
{
"_id" : ObjectId("539848b2119918654e7e90b1"),
"Country" : "Antarctica",
"Alpha2" : "AQ",
"Aplha3" : "ATA",
"Numeric" : "10",
"FIPS" : "AY",
"IGA" : ""
}
Try this:
def cursor = coll.find()
def obj = cursor.next()
while (obj.Country != 'Antarctica') {
obj = cursor.next()
}
It is inefficient, you will have to traverse the whole collection everytime to find a record, but it will end up with 'obj' being the record you need.
Try below code and see if it works.
BasicDBObject query = new BasicDBObject("Country", "Antartica");
def cursor = coll.find(query)
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
For more info look here: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/

How to build an $in query of ObjectIds using QueryBuilder with MongoDB

I am trying to build an $in query with QueryBuilder (MongoDB Java API 2.9.1). I have no problem when the query is an array of strings but when I try with an array of ObjectIds it doesn't work (returns nothing).
I am able to run the query successfully and get a result from the console:
Query in console:
db.collection.find({removed:false,app_id: {$in : [ObjectId("4f75c533ac99d845186e19b2"), ObjectId("4f75c533ac99d845186e19b3")]}})
Query created by QueryBuilder (MongoDB Java API 2.9.1):
Object[] ids;
Java code:
DBObject query = QueryBuilder.start("app_id").in(ids).and("removed").is(false).get();
ToString on DBObject produces:
{ "app_id" : { "$in" : [ { "$oid" : "4f75c533ac99d845186e19b2"}]} , "removed" : false}
Not sure if I am doing something wrong or the API doesn't support and $in query of type ObjectId. Any ideas?
Your ids should be of type org.bson.types.ObjectId so something like this should work:
import org.bson.types.ObjectId;
ObjectId[] ids = new ObjectId[]{
new ObjectId("1234568abcd"),
new ObjectId("1234567abcd")};
DBObject query = QueryBuilder.start("app_id").in(ids)
.and("removed").is(false).get();