mongodb 3.2 java driver aggregation whith match on lookup - mongodb

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

Related

mongo group with match query does not work with java

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?

Will upsert work with array Elements as well as the normal ID in MongoDB through Java driver

Mongo DB contains the following data:
The requirement is if inside this document an Field exists incremnt the counter else insert the field.
Generally we use upsert for situations when we are not sure if its going to be insert or Update.But will this work with
array Elements as well
db.arrayexample.find()
{ "_id" : "userID", "addresses" : [ { "arrayid" : NumberLong(16694), "count" : 12 } ] }
My Java code is as follows:
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb3");
MongoCollection mongoCollection = mongoDatabase.getCollection("arrayexample");
BasicDBObject query = new BasicDBObject();
query.put("_id", "userID");
query.put("addresses.arrayid",Long.valueOf(16695) );
mongoCollection.findOneAndUpdate(query,new Document("$inc", new Document("addresses.$.count", 1)),new FindOneAndUpdateOptions().upsert(true));
I am getting the following error when i run the Program:
'exception: Cannot apply the positional operator without a corresponding query field containing an array.' on server localhost:27017. The full response is
"value" : null, "errmsg" : "exception: Cannot apply the positional operator without a corresponding query field containing an array.", "code" : 16650,
Will $Upset work with array Elements as well as the normal ID
No, upserts will not work when using the $positional operator, as noted in the MongoDB documentation.
http://docs.mongodb.org/manual/reference/operator/update/positional/#upsert
Edit: As some flavour, it appears that there is an open feature request to support this particular kind of update when combined with the $setOnInsert operator within MongoDB's Jira https://jira.mongodb.org/browse/SERVER-10711

mongodb shell query with java

How to write this mongodb shell query with using java?
query : db.building_feature.find({geometry : {$geoIntersects :{$geometry :{type : "Polygon", coordinates :[[[37.59777,55.73216],[37.59805,55.77615],[37.68710,55.77643],[37.68517,55.73290],[37.59777,55.73216]]]}}}})
My collection GeoSpatialIndex is "2dsphere".
My version which is not working :
DBCollection testCollection = db.getCollection("building_feature");
final LinkedList<double[]> geo = new LinkedList<>();
geo.addLast(new double[]{37.59777, 55.73216});
geo.addLast(new double[]{37.59805, 55.77615});
geo.addLast(new double[]{37.68710, 55.77643});
geo.addLast(new double[]{37.68517, 55.73290});
final BasicDBObject query
= new BasicDBObject("geometry", new BasicDBObject("$within", new BasicDBObject("$geometry", geo)));
System.out.println("Result Count : " + testCollection.find(query).count());
Thanks.
You should write exactly the same query in Java:
BasicDBObject polygon = new BasicDBObject("type", "Polygon");
polygon.put("coordinates", <myArray>);
BasicDBObject query = new BasicDBObject(
"geometry", new BasicDBObject(
"$geoIntersects", new BasicDBObject(
"$geometry", polygon
)
)
);
<myArray> being your triple-nested double[][][] geoJSON polygon coordinates array.
Btw, it could be more clear to read with a JSON string and then JSON.parse.
And I think $whithin operator does not exist in MongoDB...

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

mongodb java to insert embedded document

I have a collection with embedded documents in it.
System
{
System_Info: ...,
Tenant: [
{
Tenant_Id: ...,
Tenant_Info: ...,
Prop_Info: ...
},
{
Tenant_Id: ...,
Tenant_Info: ...,
Prop_Info: ...
} ]
}
If I need to insert another tenant information like this
Tenant { Tenant_Id:2,Tenant_Info:"check",prop_info:"client"}.
whats the mongodb query to insert embedded documents? and how to do it using java?
Use the following code to insert into array :
BasicDBObject query = new BasicDBObject();
query.put( "System_Info", "...." );
BasicDBObject tenant = new BasicDBObject();
tenant.put("Tenant_Id", 2);
tenant.put("Tenant_Info", "check");
tenant.put("Prop_Info", "client");
BasicDBObject update = new BasicDBObject();
update.put("$push", new BasicDBObject("Tenant",tenant));
coll.update(query, update,true,true);
Are you trying to add another Tenant into the array? If so, you would want to create a DBObject representing the Tenant, and then $push it onto the array.
In Java, embedded documents are represented by DBObjects (of which BasicDBObject is a subclass). Here is an example of inserting an embedded document, from the docs:
http://www.mongodb.org/display/DOCS/Java+Tutorial#JavaTutorial-InsertingaDocument
Additionally, here is an example of using $push in Java:
Updating an array in MongoDB using Java driver
...and this is how to do it with mongo-driver version >= 3.1 (mine is 3.2.2):
Document tenant = new Document("Tenant_Id", 2)
.append("Tenant_Info", "check")
.append("Prop_Info", "client");
Bson filter = Filters.eq( "System_Info", "...." ); //get the parent-document
Bson setUpdate = Updates.push("Tenant", tenant);
coll.updateOne(filter, setUpdate);
Hope that helps someone.