i need to use mongodb java aggregate function to detect duplicated documents in collection, this is the query i ran from command line and it worked:
db.placements.aggregate(
{$group:{ "_id: "$campaign", total:{$sum:1}}},
{$match: {total: {$gt:2}}},
{$limit:10},
{$skip:0}
);
and this is the java code i wrote:
DBObject groupFields = new BasicDBObject("_id", "$campaign");
groupFields.put("total", new BasicDBObject("$sum", 1));
DBObject group = new BasicDBObject("$group", groupFields);
DBObject matchFields = new BasicDBObject("total", new BasicDBObject("$gt", 2));
DBObject match = new BasicDBObject("$match", matchFields);
collection.aggregate(match, group, new BasicDBObject("$skip", 0), new BasicDBObject("$limit", 10));
but it always return empty result. can anyone tell me what's wrong?
Related
I am looking for solutions to get field name and type for all nested fields including array of documents using $project $mergeobjects, $objectToArray , $unwind.
collection.aggregate(Arrays.asList(
new Document("$limit",100),
new Document("$project", new Document("fields", new Document("$objectToArray", "$ROOT" ))),
new Document("$unwind", "$fields"),
new Document("$project", new Document("fields", new Document("k", "$fields.k").append("v",new Document("$type", "$fields.v")))),
new Document("$group", new Document("_id", "$fields.k").append("fields", new Document("$first", "$fields"))),
new Document("$group", new Document("_id", null).append("fields", new Document("$push", "$fields"))),
new Document("$project", new Document("fields", new Document("$arrayToObject", "$fields" )))
));
I have tried implementing but could not process array of documents yet. I am trying to learn how to use $mergeObjects to achieve the output
I am trying to fetch the data from the MongoDB to get the top 5 most liked products.
But I'm getting below error. (MongoDB version 3.2.21)
com.mongodb.MongoCommandException: Command failed with error 9: 'The 'cursor' option is required, except for aggregate with the explain argument' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "The 'cursor' option is required, except for aggregate with the explain argument", "code" : 9, "codeName" : "FailedToParse" }
DBObject groupFields = groupFields = new BasicDBObject("_id", 0);
groupFields.put("_id", "$productId");
groupFields.put("avgRating", new BasicDBObject("$avg", "$productRvR"));
groupFields.put("productModelName", new BasicDBObject("$push", "$productMN"));
DBObject group = new BasicDBObject("$group", groupFields);
DBObject projectFields = new BasicDBObject("_id", 0);
projectFields.put("productId", "$_id");
projectFields.put("avgRating", "$avgRating");
projectFields.put("productModelName", "$productModelName");
DBObject project = new BasicDBObject("$project", projectFields);
DBObject sort = new BasicDBObject();
sort.put("avgRating",-1);
DBObject orderby=new BasicDBObject("$sort",sort);
DBObject limit=new BasicDBObject("$limit",5);
AggregationOutput aggregate userReviews.aggregate(group,project,orderby,limit);
LinkedHashMap<String, String> mostLikedProductsMap = new LinkedHashMap<String, String>();
for (DBObject queryResult : aggregate.results()) {
BasicDBObject obj = (BasicDBObject) queryResult;
BasicDBList productModelName = (BasicDBList) obj.get("productModelName");
mostLikedProductsMap.put((String)productModelName.get(0),obj.getString("avgRating"));
}
return mostLikedProductsMap;
I'm struggling to create a Morphia query (using the typed query class Query<T>) to implement the following:
db.getCollection('Order').find({'orderLines.trackingDetails': {$elemMatch: {deliveryDate: {$exists: false}}}})
The struggle is how to code for the {$exists: false} (to return only records where the trackingDetails has an element where deliveryDate does not exist).
I figured it out:
DBObject query = BasicDBObjectBuilder.start()
.add("orderLines.trackingDetails",
new BasicDBObject("$elemMatch",
new BasicDBObject("deliveryDate",
new BasicDBObject("$exists", false))))
.get();
Query<Order> q = datastore.createQuery(Order.class, query);
I'd like to learn how to implement group by query using Mongo DB Java 3.x Driver. I want to group my collection through the usernames, and sort the results by the count of results DESC.
Here is the shell query which I want to implement the Java equivalent:
db.stream.aggregate({ $group: {_id: '$username', tweetCount: {$sum: 1} } }, { $sort: {tweetCount: -1} } );
Here is the Java code that I have implemented:
BasicDBObject groupFields = new BasicDBObject("_id", "username");
// count the results and store into countOfResults
groupFields.put("countOfResults", new BasicDBObject("$sum", 1));
BasicDBObject group = new BasicDBObject("$group", groupFields);
// sort the results by countOfResults DESC
BasicDBObject sortFields = new BasicDBObject("countOfResults", -1);
BasicDBObject sort = new BasicDBObject("$sort", sortFields);
List < BasicDBObject > pipeline = new ArrayList < BasicDBObject > ();
pipeline.add(group);
pipeline.add(sort);
AggregateIterable < Document > output = collection.aggregate(pipeline);
The result I need is the count of documents grouped by username. countOfResults returns the total number of the documents the collection has.
You should try not to use old object (BasicDBObject) types with Mongo 3.x. You can try something like this.
import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static java.util.Arrays.asList;
Bson group = group("$username", sum("tweetCount", 1));
Bson sort = sort(new Document("tweetCount", -1));
AggregateIterable <Document> output = collection.aggregate(asList(group, sort));
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...