How to get specific value from sub-document in mongo - java

I want to find the specific field value from mongo sub-document, but its retrieving either full data or null value. I am using mongo 3.0.1 driver. Is there any issue with the syntax for the mongo specific driver.
Json data is:
{
"Demo": {
"Demo Data": {
"Building": {
"A": 1,
"B": 2,
"C": 3,
"D": 4,
},
"Mode": "Building"
}
}
}
The code is as below:
DBCollection collection = db.getCollection("demo");
BasicDBObject field = new BasicDBObject();
BasicDBObject document = new BasicDBObject();
field1.put("_id", 0);
field1.put("Demo", 1);
DBCursor cursor = collection.find(document, field);
BasicDBObject object = new BasicDBObject();
BasicDBObject Mode = new BasicDBObject();
while (cursor.hasNext()) {
object = (BasicDBObject) cursor.next();
Mode.put("Mode", object.get(Mode));
System.out.println("Mode value is"+Mode);
}
but using above code, the output showing as:
Mode value is {"Mode":null}
The requirement is to get the following output:
{"Mode": "Building"}.
Please specify where the condition went wrong. Thanks for any help.

I think you are incorrectly assuming that since you have put field1.put("Demo", 1); , it would return you inner document, whereas no matter what it would always return you full document what it will do is omit other fields, but even then it would be full document which is right from the root.
while (cursor.hasNext()) {
object = (BasicDBObject) cursor.next();
Map map = object.toMap();
Mode.put("Mode", map.get("Demo").get("Demo Data").get("Mode")); //pre-check for NPE
System.out.println("Mode value is"+Mode);
}

Related

Retrieve only the queried element in an object array in MongoDB using java

Suppose we have the following documents in a MongoDB collection:
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"shapes":[
{
"shape":"square",
"color":"blue"
},
{
"shape":"circle",
"color":"red"
}
]
},
{
"_id":ObjectId("562e7c594c12942f08fe4193"),
"shapes":[
{
"shape":"square",
"color":"black"
},
{
"shape":"circle",
"color":"green"
}
]
}
And the MongoDB query is
db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});
Can someone tell me how to write it in Java?
I am using:
List<BasicDBObject> obj = new ArrayList<>();
obj1.add(new BasicDBObject("shapes.color", "red"));
List<BasicDBObject> obj1 = new ArrayList<>();
obj2.add(new BasicDBObject("shapes.$", "1"));
BasicDBObject parameters1 = new BasicDBObject();
parameters1.put("$and", obj1);
DBCursor cursor = table.find(parameters1,obj2).limit(500);
and I am not getting anything.
The syntax of the Mongo Shell find function is:
db.collection.find(query, projection)
query document Optional. Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass an empty document ({}).
projection document Optional. Specifies the fields to return in the documents that match the query filter.
When translating this for execution by the Mongo Java driver you need to construct separate BasicDBObject instances for;
the query
the projection
Here's an example:
MongoCollection<Document> table = ...;
// {"shapes.color": "red"}
BasicDBObject query = new BasicDBObject("shapes.color", "red");
// {_id: 0, 'shapes.$': 1}
BasicDBObject projection = new BasicDBObject("shapes.$", "1").append("_id", 0);
FindIterable<Document> documents = table
// assign the query
.find(query)
// assign the projection
.projection(projection);
System.out.println(documents.first().toJson());
Given the sample documents included in your question the above code will print out:
{
"shapes": [
{
"shape": "circle",
"color": "red"
}
]
}
This is identical to the output from db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});.

How to use $in operator in mongodb with two fields in java

I would like to retrieve the following information:
select names from database where address like 'colombo' and age>20;
but for MongoDB in Java. Essentially, it should return all names that contain the word colombo ang age greater than 20 in them. I know that there is the $in operator in MongoDB, but how do I do the same in Java, using the Java driver? I've been trying to look for it everywhere but am getting nothing. I've tried:
query = new BasicDBObject("names", new BasicDBObject("$in", "colombo"), new BasicDBObject("age", "$gt20"));
But it didn't worked :( Please help!
Try this
BasicDBObject query = new BasicDBObject("names", new BasicDBObject("$in", Arrays.asList("colombo")));
query.append("age", new BasicDBObject("$gt", 20));
FindIterable<Document> find = collection.find(query);
MongoCursor<Document> iterator = find.iterator();
Document doc = null;
while (iterator.hasNext()) {
doc = iterator.next();
System.out.println(doc);
}
The $in operator will not be suitable for such as you can only use it to match values that are in an array or to search for documents where the value of a field equals any value in a specified array.
In your case you need a $regex operator to fulfil the query by performing a SQL LIKE operation:
db.collection.find({
"names": { "$regex": /colombo/, "$options": "i" },
"age": { "$gt": 20 }
})
or
db.collection.find({
"names": /colombo/i },
"age": { "$gt": 20 }
})
which can be implemented in Java as
Pattern pattern = Pattern.compile("colombo", Pattern.CASE_INSENSITIVE);
BasicDBObject query = new BasicDBObject("names", pattern)
.append("$age", new BasicDBObject("$gt", 20));
DBCursor result = coll.find(query);
If using the 3.0.x and newer drivers:
Document regx = new Document();
regx.append("$regex", "(?)" + Pattern.quote("colombo"));
regx.append("$options", "i");
Document query = new Document("names", regx).append("$age", new Document("$gt", 20));
FindIterable<Document> iterable = db.getCollection("coll").find(query);

How to find if a key exists in MongoDb document?

I have the following mongodb document
{
"user_100":{
"name": "Scott" ,
"uniqueDetails":{
"mobile":"9999999999",
"email": "scott#abc.com",
}
},
"user_101":{
"name": "Smith",
"uniqueDetails":{
"mobile":"9999999998",
"email": "smith#abc.com"
}
}
}
Now, when a new user signs up, I would like to check if a given mobile number/email already exists. Is there any solution for this with Java MongoDB API.
You can do a query and search in the collection for the tags that you want:
For example:
BasicDBObject query = new BasicDBObject("email", email_to_seach);
DBCursor cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
Also, you can look for only the first document that has the email or mobile phone that you want, with:
BasicDBObject query = new BasicDBObject("email", email_to_seach);
DBObject myDoc = coll.findOne(query);
You can use the com.mongodb.QueryBuilder class to build a query:
DBObject query = QueryBuilder.start("mobile").is(mobileNumberToSearch)
.or(QueryBuilder.start("email").is(emailToSearch).get()).get();
DBCursor dbCursor = collection.find(query);
if(dbCursor.hasNext()){
System.out.println("mobile number or email already exists");
}

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

Add projection to morphia query

When doing queries with Morphia is it possible to limit the returned fields (specify a projection)?
Like this on the command line:
db.Institution.find({name: /^Berlin/}, {slug:1})
Or this with the Java driver:
BasicDBObject projection = new BasicDBObject("slug", 1);
collection.find(new BasicDBObject(),projection);
Thanks
You do, see https://code.google.com/p/morphia/wiki/Query#Ignoring_Fields
Pattern regex = Pattern.compile("^Berlin");
Query<InsitutionEntity> query = mongoDataStore.find(InsitutionEntity.class)
.field("name").equal(regex)
.retrievedFields(true, "slug").asList();
(Didn't test it, but it should work like this)
BasicDBObject filter = new BasicDBObject();
filter.append("name", "whoever");
BasicDBObject projection = new BasicDBObject();
projection.append("fieldOne", 1); // 1 == True, it shows the Field.
projection.append("fieldTwo", 1);
projection.append("_id", 0) // 0 == False, it does not show the "_id"
List list = MorphiaObject.datastore.getCollection(MyClass.class).find(filter, projection).toArray();
for (Object each : list) {
System.out.println("Each: " + each.toString());
}

Categories

Resources