i am trying transfer the PostgreSQL for MongoDB using java.
I have the SQL
SELECT id_buyer, buyer, SUM(qtde)
FROM test.log
GROUP BY id_buyer, buyer
and my new code
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("teste");
MongoCollection<Document> coll = db.getCollection("log");
DBObject groupFields = new BasicDBObject();
groupFields.put("id_buyer", "$id_buyer");
groupFields.put("buyer", "$buyer");
AggregateIterable<Document> mongoCollectionList = coll.aggregate(
Arrays.asList(
Aggregates.group(groupFields, Accumulators.sum("qtde", "$qtde")),
Aggregates.project(fields(include("comprador", "Quantidade")))
));
MongoCursor<Document> mongoCursor = mongoCollectionList.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next().toJson());
}
result
{ "_id" : { "id_buyer" : 2, "buyer" : "COMPS" }, "qtde" : 16703 }
How do i remove "id_buyer" and "buyer" that is into "_id" ?
Tks
you try like this..
AggregateIterable<Document> mongoCollectionList = collection.aggregate(
Arrays.asList(
Aggregates.group(groupFields, Accumulators.sum("qtde", "$qtde")),
Aggregates.project(Projections.fields(Projections.include("qtde"),Projections.excludeId()))
));
I have tested the answer posted by Veeram and it worked perfectly for me.
This was his sugestion:
Aggregates.project(fields(excludeId(),
computed("id_buyer", "$_id.id_buyer"),
computed("buyer", "$_id.buyer"),
include("comprador", "Quantidade")));
Related
I want to run raw mongoDb queries using runCommand() which takes in BSON data.
Following is my code
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("MyDB");
MongoCollection<Document> collection = (MongoCollection<Document>)database.runCommand(??);
If my query is
db.mycol.find({"by":"tutorials point"}).
What should be BSON data that I have to pass inside runCommand() ? Is it only
{{"by":"tutorials point"}}
or
db.mycol.find({"by":"tutorials point"}).
And If instead of find() i have to use Insert() how to go about it ??
Find:
db.runCommand({
find: "mycol",
filter: { by: "tutorials point"}
})
Insert:
db.runCommand({
insert: "mycol",
documents: [ { _id: 1, foo: "bar"} ]
})
I think the easiest why to do it in java is to use Jongo (http://jongo.org/).
Syntax is very similar to mongo shell.
jongo.runCommand("{find: 'mycol', filter: { by: 'tutorials point'}}")
You can not do that.
First of all you need to get your collection
like : MongoCollection<Document> collection = database.getCollection("test");
Once you have the collection you can run the raw query by using the util import com.mongodb.util.JSON;
this would be an example that you want to do:
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("MyDB");
MongoCollection<Document> collection = database.getCollection("mycol");
String rawQuery = "{\"by\": \"tutorials point\"}";
DBObject query = (DBObject) JSON.parse(rawQuery);
collection.find(query);
Give example of how it work
this was my query
db.getCollection('Collection').aggregate([{
$unwind: '$somearray'
}, {
$match: {
_id: ObjectId("123456"),
'somearray.type': "blabla"
}
}, {
$project: {
'_id':0,
'name': '$somearray.name',
'phone': '$phone'
}
}])
This was my Java program that did the same as query
public MongoIterable < Document > GetList(String collectionName, String id) {
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("MyDB");
MongoCollection < Document > collection = database.getCollection("collectionName");
Document match = Document.parse("{_id: ObjectId('" + id + "'),'somearray.type': 'blabla'}");
Document project = Document.parse("{ $project: { _id: 0,'name': '$somearray.name'}, 'phone': '$phone'}");
MongoIterable < Document > output = collection.aggregate(Arrays.asList(Aggregates.unwind("$somearray"), Aggregates.match(match), project));
return output;
}
I'm trying to query mongodb with java. The name of my collection is: reads. Here is an example of a specific document I'm querying for:
{
"_id" : {
"d" : "B66929932",
"r" : "15500304",
"eT" : ISODate("2014-09-29T12:03:00Z")
},
"v" : 169000,
"iT" : ISODate("2015-04-10T20:42:07.577Z")
}
I'm trying to query where r = 15500304, eT = 2014-09-29T12:03:00Z and v = 169000. I'm able to do this in mongo pretty easily:
db.reads.find({ "_id.r" : "15500304", "_id.eT" : ISODate("2014-09-29T12:03:00Z"), "$where" : "this.v == 169000;"}).pretty()
I'm unable to figure out how to structure this in java. So far I've got:
DBCollection collection = db.getCollection("reads");
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("_id.r", "15500304"));
obj.add(new BasicDBObject("_id.eT", "2014-09-29T12:03:00Z"));
obj.add(new BasicDBObject("v", 169000));
andQuery.put("$and", obj);
DBCursor cursor = collection.find(andQuery);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
My Question is: How do I query using these child nodes and return the matching document?
I'm unable to find any clear advice/examples online. Any and all advice is very appreciated.
You were close. Modify your query to:
DBCollection collection = db.getCollection("reads");
BasicDBObject query = new BasicDBObject();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String dateInString = "2014-09-29T12:03:00Z";
Date date = df.parse(dateInString);
query.append("status.name", "Expired")
.append("_id.eT", date)
.append("v", 169000);
Or using QueryBuilder:
DBObject query = QueryBuilder.start()
.put("_id.r").is("15500304")
.put("_id.eT").is(date)
.put("v").is(169000)
.get();
DBCursor cursor = collection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
This statement works fine in mongo console:
db.system_integrator.find( { person_name: { $in: [ "Mick Jagger", "Bob Dyla", "Tony Orlando" ] } } )
I'm trying to build equivalent one in java using QueryBuilder as following:
DBObject query = new BasicDBObject();
query.put(dbFieldName, "[ \"Mick Jagger\", \"Bob Dyla\", \"Tony Orlando\" ]");
qb.in( query );
however this way of building a query doesn't work. What I'm doing wrong here?
You can do this in Java as follows :
BasicDBList list = new BasicDBList();
list.add("Mick Jagger");
list.add("Bob Dyla");
list.add("Tony Orlando");
QueryBuilder qb = new QueryBuilder();
qb.put("person_name").in(list);
or
BasicDBList list = new BasicDBList();
list.add("Mick Jagger");
list.add("Bob Dyla");
list.add("Tony Orlando");
DBObject query = new BasicDBObject();
query.put("person_name", new BasicDBObject("$in", list));
I'm using mongo 2.2.3 and the java driver.
My dilemma, I have to $push a field and value into an array, but I cant seem to figure out how to do this. A sample of my data:
"_id" : 1,
"scores" : [
{
"type" : "homework",
"score" : 78.97979
},
{
"type" : "homework",
"score" : 6.99
},
{
"type" : "quiz",
"score" : 99
}
]
I can $push in the shell:
db.collection.update({_id:1},{$push:{scores:{type:"quiz", score:99}}})
but it's when I translate this into java I confuse my self and chuck my keyboard at a wall.
my java code (incomplete and wrong) so far:
DBObject find = new BasicDBObject("_id", 1);
DBObject push = new BasicDBObject("$push", new BasicDBObject(
"scores", new BasicDBObject()));
DBObject listItem = new BasicDBObject("scores", new BasicDBObject("type","quiz").append("score",99));
DBObject updateQuery = new BasicDBObject("$push", listItem);
myCol.update(findQuery, updateQuery);
Since mongodb-driver 3.1. there is a builder class com.mongodb.client.model.Updates with appropriate methods for each update case. In this case this would be:
Document score = new Document().append("type", "quiz")
.append("score",99);
collection.updateOne(eq("_id", "1"),Updates.addToSet("scores", score));
If you're more comforable with the query format of the shell, you may find it's easier to use JSON.parse to contstruct your DBObject for the $push:
import com.mongodb.util.JSON;
String json = "{$push:{scores:{type:'quiz', score:99}}}";
DBObject push = (DBObject) JSON.parse(json);
Using Jongo, you can do as in the shell:
db.collection.update({_id:1},{$push:{scores:{type:"quiz", score:99}}})
Becomes in Java:
collection.update("{_id:1}").with("{$push:{scores:{type:#, score:#}}}", "quiz", 99);
No fancy DBObject needed ;-)
MongoDB Java driver can simplify this. Use $each instead of $push.
$each mongodb reference document
Java sample -
BasicDBObject addressSpec = new BasicDBObject();
addressSpec.put("id", new ObjectId().toString());
addressSpec.put("name", "one");
BasicDBObject addressSpec2 = new BasicDBObject();
addressSpec2.put("id", new ObjectId().toString());
addressSpec2.put("name", "two");
List<BasicDBObject> list = new ArrayList<>();
list.add(addressSpec); list.add(addressSpec2);
UpdateResult updateOne = individualCollection.updateOne(Filters.eq("_id", "5b7c6b612612242a6d34ebb6"),
Updates.pushEach("subCategories", list));
How can I make this query in Java
db.comments.find({ "hsID.$id" { "$oid" : "4fe71a50e7e9f22ae5fb96bf"}} , {commentList: { $slice : [ 2 , 2]}});
This the code I am doing
BasicDBObject query = new BasicDBObject();
BasicDBObject allFields = new BasicDBObject();
ObjectId objectId = new ObjectId(objId);
query.put("{hsID.$id", objectId);
Integer[] sliceInt = { startIndex, pageSize };
query.put(
"commentList",
new BasicDBObject().append("$slice", sliceInt));
DBCursor resultsCursor = CommentColl.find(allFields,query);
and the output is
And the output is
query = { "{hsID.$id" : { "$oid" : "4fe71a50e7e9f22ae5fb96bf"} , "commentList" : { "$slice" : [ 2 , 2]}}
Thanks for your help
You need to separate the query from the fields you want returned. Try something more like this:
BasicDBObject query = new BasicDBObject("hsID.$id", new ObjectId(objId));
BasicDBObject fields = new BasicDBObject(
"commentList",
new BasicDBObject("$slice", new int[] { startIndex, pageSize }));
DBCursor resultsCursor = CommentColl.find(query, fields);
Notice also that I removed the opening curly brace that you had preceding hsid.$id.