How to Query MongoDB Using Child Nodes in Java - java

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

Related

MongoDB with Java - GroupBy more one column

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

How to convert mongo shell query to java basicDBObject?

I am having following mongo query which is executed in mongo shell.
db.test.update({
uuid: "160597270101684",
sessionId: "160597270101684.1"
}, {
$setOnInsert: {
stamps: {
currentVisit: "1377500985",
lastVisit: "1377500985"
}
},
$push:{
visits: {
page: "google.com",
method: "GET"
}
}
}, { upsert:true })
Because i am new to java, I am little bit confused to create the basicDBObject.
I had tried like this for sample
BasicDBObject doc = new BasicDBObject("uuid",1).append("session",2);
BasicDBObject upsertion = new BasicDBObject("upsert",true);
collection.update(doc,upsertion);
But its not working.
Any help will be great.
The upsert option isn't specified with a DBObject but with a third argument to DBCollection.update
public WriteResult update(DBObject q, DBObject o, boolean upsert, boolean multi)
You'll need to form a DBObject for update by appending $setOnInsert, $push, stamps and visits.
BasicDBObject update = new BasicDBObject();
BasicDBObject stamps = new BasicDBObject();
stamps.append("currentVisit", "1377500985").append("lastVisit", "1377500985");
BasicDBObject visits = new BasicDBObject();
update.append("$setOnInsert", stamps).append("$push", visits);
collection.update(doc, update, true);

MongoDB $in with $and Query

Is this type of query possible?
I need to query the database for data for a specified date for a set of specified stocks. So the data needs to have "this" date and be one of "these" symbols.
I have the following code:
public void findDateStockSet(String date, ArrayList<String> symbolSet) throws UnknownHostException {
this.stocks = this.getCollectionFromDB();
BasicDBObject objectToFind = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("date", date));
obj.add(new BasicDBObject("symbol", new BasicDBObject("$in", symbolSet)));
objectToFind.put("$and", obj);
DBCursor cursor = this.stocks.find(objectToFind);
System.out.println("Finding Stocks");
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println();
}
This always comes up null. Can someone explain how to make a query like this work?
You don't need to use $and operator, just build the query as the json below:
{ "date" : "20100223", "symbol" : { $in : [ "appl", "goog" ] } }
I like to use BasicDBObjectBuilder util class to build DBObjects. So your query will be:
DBObject query = BasicDBObjectBuilder.start()
.add("date", date)
.push("symbol")
.add("$in", symbolSet)
.get();

Java MongoDB Query

I have a structure like this in my database:
{
{
"document_id" : 35,
"transport" : ["car", "plane", "train", "boat"]
},
{
"document_id" : 36,
"transport" : ["car", "bike", "train"]
}
}
How would I do a search query to find a document/record with for example transport 'plane'?
Thanks for any help.
Steven
from MongoShell
db.find({transport:"plane"}) would do.
MongoDB will search the entire array to match the query in case the value is an array.
Using Java Driver.
Yous first get the Mongo collection
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
BasicDBObject dbo = new BasicDBObject();
dbo.append("transport", "plane");
DBCursor cur = collection.find(dbo);
while (cur.hasNext()) {
list.add(JSONHelper.toJSON(cur.next().toMap()));
}
To search for an array containing an element, you can just check for that element against the array.
So, just using: -
db.collection.find({transport:"plane"})
would give you what you want.
Here's the implementation in Java: -
BasicDBObject doc = new BasicDBObject("document_id", 35)
.append("transport", new String[] {"car", "plane"});
BasicDBObject doc2 = new BasicDBObject("document_id", 36)
.append("transport", new String[] {"car"});
coll.insert(doc);
coll.insert(doc2);
DBObject query = new BasicDBObject("transport", "plane");
DBCursor cursor = coll.find(query, new BasicDBObject("_id", 0));
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
Output : -
{ "document_id" : 35 , "transport" : [ "car" , "plane"]}
#Document(collection = "document")
public class Transport {
private ObjectId document_id;
private ArrayList transport;
}
//
   List<String> list = new ArrayList<String>();
        list.add("car");
        list.add("plane");
   list.add("train");
        list.add("boat");
Transport transport;
transport.setTransport(list);

$slice mongoDB Java

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.

Categories

Resources