I have tried to fetch data for the particular column value in the mongo document but its displaying whole data.
Following is the mongo document:
{
"_id" : ObjectId("59db2321811a592384865711"),
"User_ID" : "demo",
"Project_ID" : "demo-1",
"Project_Information" : {
"Project_Description" : "Sample",
"Primary_Building_Type" : "Office",
"State" : "AR",
"Analysis_Type" : "1",
"Project_Billing_Number" : "WY",
"Country" : "USA",
"Climate_Zone" : "3A",
"Zip_Code" : "71611"
"City" : "WA",
"Units" : "IP"
}
}
I want to fetch the following output:
[
{
"User_ID": "demo",
"Project_Description": "Sample"
}]
I have tried using dot: Project_Information.Project_Description.The code is as below:
public Object[] addDemo1(String User_ID) throws Exception {
DB db = ConnectToDB.getConnection();
Properties prop = new Properties();
InputStream input = null;
input = GetProjectStatus.class.getClassLoader().getResourceAsStream("config.properties");
prop.load(input);
String col = prop.getProperty("COLLECTION_PI");
System.out.println("data is.." + col);
DBCollection collection = db.getCollection(col);
BasicDBObject obj = new BasicDBObject();
BasicDBObject fields = new BasicDBObject();
BasicDBObject fields2 = new BasicDBObject();
List<DBObject> obj1 = null;
if (User_ID != null && !User_ID.equals("") && User_ID.length() > 0) {
obj.put("User_ID", User_ID);
fields.put("_id", 0);
fields.put("User_ID", 1);
fields.put("Project_ID", 1);
fields.append("Project_Information.Project_Description", "Project_Description");
BasicDBObject fields1 = new BasicDBObject();
fields1.put("User_ID", User_ID);
}
DBCursor cursor = collection.find(obj, fields);
System.out.println("count is:" + cursor.count());
obj1 = cursor.toArray();
System.out.println("" + obj1);
cursor.close();
db.getMongo().close();
return obj1.toArray();
}
But it displays the whole structure of Project_Information.
Please specify how to achieve this. Thanks for help.
Using a 2.x MongoDB Java Driver
Here's an example using the MongoDB 2.x Java driver:
DBCollection collection = mongoClient.getDB("stackoverflow").getCollection("demo");
BasicDBObject filter = new BasicDBObject();
BasicDBObject projection = new BasicDBObject();
// project on "Project_Information.Project_Description"
projection.put("Project_Information.Project_Description", 1);
DBCursor documents = collection.find(filter, projection);
for (DBObject document : documents) {
// the response contains a sub document under the key: "Project_Information"
DBObject projectInformation = (DBObject) document.get("Project_Information");
// the "Project_Description" is in this sub document
String projectDescription = (String) projectInformation.get("Project_Description");
// prints "Sample"
System.out.println(projectDescription);
// to return this single String value in an Object[] (as implied by your OP) just do create the Object[] like this and then return it ...
Object[] r = new Object[] {projectDescription};
// prints the entire projected document e.g.
// { "_id" : { "$oid" : "59db2321811a592384865711" }, "Project_Information" : { "Project_Description" : "Sample" } }
System.out.println(document.toString());
}
Using a 3.x MongoDB Java Driver
Here's an example using the MongoDB 3.x Java driver:
// this finds all documents in a given collection (note: no parameter supplied to the find() call)
// and for each document it projects on Project_Information.Project_Description
FindIterable<Document> documents =
mongoClient.getDatabase("...").getCollection("...")
.find()
// for each attrbute you want to project you must include its dot notation path and the value 1 ...
// this is the equivalent of specifying {'Project_Information.Project_Description': 1} in the MongoDB shell
.projection(new Document("Project_Information.Project_Description", 1));
for (Document document : documents) {
// the response contains a sub document under the key: "Project_Information"
Document projectInformation = (Document) document.get("Project_Information");
// the "Project_Description" is in this sub document
String projectDescription = projectInformation.getString("Project_Description");
// prints "Sample"
System.out.println(projectDescription);
// to return this single String value in an Object[] (as implied by your OP) just do create the Object[] like this and then return it ...
Object[] r = new Object[] {projectDescription};
// prints the entire projected document e.g. { "_id" : { "$oid" : "59db2321811a592384865711" }, "Project_Information" : { "Project_Description" : "Sample" } }
System.out.println(document.toJson());
}
Java libraries won't let you directly access using dot.
They have build in getter and setter methods.
You have not mentioned which package you are using.
Here's the query that you need:
db.mycol.find({},{User_ID:1,"Project_Information.Project_Description":1})
It will give:
{ "_id" : ObjectId("59db2321811a592384865711"),
"User_ID" : "demo",
"Project_Information" : { "Project_Description" : "Sample" }
}
You will have to convert the query in whatever format your package accepts.
Here's a tutorial:
https://www.mongodb.com/blog/post/getting-started-with-mongodb-and-java-part-i
Related
I want to parse a java string to mongo DBObject or BasicDBObject as below.
List<DBObject> query = new ArrayList<DBObject>();
String allQry = "{ \"$match\" : { \"CUSTOMERID\" : { \"$gt\" : 10}}}, { \"$project\" : { \"CUSTOMERNAME\" : 1 , \"COUNTRY\" : 1 , \"CUSTOMERID\" : 1}},{ \"$sort\" : { \"COUNTRY\" : 1}}";
BasicDBObject dbobj = BasicDBObject.parse(allQry);
query.add(dbobj);
System.out.println("qqqquery : "+query);
Cursor aggCur = collection.aggregate(query, aggOpt);
After run above example codes, it outputs qqqquery : [{ "$match" : { "CUSTOMERID" : { "$gt" : 10}}}]. There are $match , $project and $sort in allQry. Why do not it includes $project and $sort in this query? It only includes $match, who can help to check this reason? Thanks.
Following this tutorial:
http://pingax.com/trick-convert-mongo-shell-query-equivalent-java-objects/
you could add all parts of your query like this:
MongoClient mongo = new MongoClient();
DB db = mongo.getDB("pingax");
DBCollection coll = db.getCollection("aggregationExample");
/*
MONGO SHELL : db.aggregationExample.aggregate(
{$match : {type : "local"}} ,
{$project : { department : 1 , amount : 1 }}
);
*/
DBObject match = new BasicDBObject("$match", new BasicDBObject("type", "local"));
DBObject project = new BasicDBObject("$project", new BasicDBObject("department", 1).append("amount", 1));
AggregationOutput output = coll.aggregate(match,project,group,sort);
Related:
How to find documents matching multiple criteria
Executing Mongo like Query (JSON)through Java
when i use this query on mongo shell
db.matchgrup.aggregate([{$match:{ "longitude" : {"$gte":73.8172198689148,"$lte":73.8200133489148}, "latitude" :{"$gte":19.98591316489416,"$lte":19.98870664489416} }},{ "$group": {"_id":null, "band_4" : { "$avg" : "$band_4"},"band_8":{"$avg":"$band_8"} } }])
it return
{ "_id" : null, "band_4" : 1578.8266666666666, "band_8" : 2649.0155555555557 }
but when i used mongo java driver for same query
searchQuery1 =new BasicDBObject("longitude", new BasicDBObject("$gte", X.doubleValue()).append("$lte", px1.doubleValue()));
criteria.add(searchQuery1);
searchQuery2=new BasicDBObject("latitude", new BasicDBObject("$gte", py2.doubleValue()).append("$lte", Y.doubleValue() ));
criteria.add(searchQuery2);
query2=new BasicDBObject("$and",criteria);
group1 = new BasicDBObject();
group1.put("_id", null);
group1.put("band_4", new BasicDBObject("$avg", "$band_4"));
group1.put("band_8", new BasicDBObject("$avg", "$band_8"));
output = coll.aggregate(
new BasicDBObject("$match",query2),
new BasicDBObject("$group",group1));
for (DBObject doc : output.results()) {
band4=(Double)doc.get("band_4");
band8=(Double)doc.get("band_8");
}
and it doesn't retuen any value and doesnt goes inside of for loop of doc
can anybody help me out what m doing wrong
I have this in my db.
{
"_id" : ObjectId("59424f41baaacf1f40815ae8"),
"first_name" : "Yazid",
"last_name" : "Amir",
"gender" : "Male",
"hobby" : ["Memanah", "Business", "Fusal", "Makan"]
}
Let say that I want to retrieve the "Business" from array hobby. So my code will be like this
MongoCollection collection = db.getCollection("customers");
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("first_name", "Yazid");
MongoCursor<Document> cursor = collection.find(whereQuery).iterator();
try {
while (cursor.hasNext()) {
Document str = cursor.next();
out.println(str.get("hobby.0")); // display specific field
}
} finally {
cursor.close();
}
However, the result is null.
Use a List<Document> to store your array
while (cursor.hasNext()) {
Document str = cursor.next();
List<Document> list = (List<Document>)str.get("hobby");
out.println(list.get(0)); // display specific field
}
I have a set of ID's of documents which I add previously in MongoDB.
Then I try to get Document from ID.
String idString = "57f8f50977c8a5b8757f261a";
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id", idString);
DBCursor cursor = table.find(whereQuery);
if(cursor.hasNext())
{
System.out.println("FOUND!" + cursor.next());
}
I get zero results.
But, if I call another field
It works and return me document.
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("datachain", "AA");
DBCursor cursor = table.find(whereQuery);
if(cursor.hasNext())
{
System.out.println("FOUND!" + cursor.next());
}
FOUND!{ "_id" : { "$oid" : "57f8f50977c8a5b8757f261b"} , "datachain" : "AA" , "createdDate" : { "$date" : "2016-10-08T13:30:49.588Z"}}
What I do wrong? Why I can't find document by ID's?
Thnx!
UPD:
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id", new ObjectId("57f8f50977c8a5b8757f261a"));
DBCursor cursor = table.find(whereQuery);
Same, no result founded.
You have to pass the idString as an ObjectId.
whereQuery.put("_id", new ObjectId(idString));
I have a collection containing contacts and each contact document has a firstName and lastName attribute.
Now I want to query the database by using Java and the MongoDb Java driver in version 3.2.
I try to find a contact with a concatenated firstName + lastName. My query looks like the following for the MongoDb shell:
db.getCollection('contacts').aggregate(
{
$project:{
fullName:{
$concat: [ "$firstName", " ", "$lastName" ]
}
}
},
{
$match:{
fullName:"John Doe"
}
}
);
Now I tried to get my head around the MongoDb Java driver to get the same accomplished in Java:
AggregateIterable<Document> documents = contactUserCollection.aggregate(Arrays.asList(project(computed("fullName", "$firstName $lastName")), match(eq("fullName", firstLastName))));
But this isn't working.
Does someone have an idea how I could accomplish this?
Thank you
You could try the following:
/*
MONGO SHELL :
var pipeline = [
{
"$project": {
"otherfieldsA": 1,
"otherfieldsB": 1,
"otherfieldsC": 1,
"fullName": {
"$concat": [ "$fistName", " ", "$lastName" ]
}
}
}
{
"$match": { "fullName": "John Doe" }
}
];
db.contacts.aggregate(pipeline);
*/
public class JavaAggregation {
public static void main(String args[]) throws UnknownHostException {
MongoClient mongo = new MongoClient();
DB db = mongo.getDB("test");
DBCollection coll = db.getCollection("contacts");
// create the pipeline operations, build the $project operations
BasicDBList concatenate = new BasicDBList();
concatenate.add("$firstName");
concatenate.add(" ");
concatenate.add("$lastName");
DBObject fullName = new BasicDBObject("$concat", concatenate);
DBObject fields = new BasicDBObject("otherfieldsA", 1);
fields.put("otherfieldsB", 1);
fields.put("otherfieldsC", 1);
fields.put("fullName", fullName);
DBObject project = new BasicDBObject("$project", fields);
// create the $match operator
DBObject match = new BasicDBObject("$match",
new BasicDBObject("fullName", "John Doe")
);
AggregationOutput documents = coll.aggregate(match, project, group, sort);
for (DBObject result : documents.results()) {
System.out.println(result);
}
}
}