How to retrieve a value from mongoDB, by its key name? - java

I am new to mongoDB. I am using java and mongoDB. I have a json like,
[{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"} , "HomeTown" : "AA" ,
"PhoneNumber" : { "CustName" : "xxx" , "Number" : "3403290"},
"MobileNumber" : { "CustName" : "yyy" , "Number" : "9323304302"}}]
[{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"} , "HomeTown" : "AA" ,
"PhoneNumber" : { "CustName" : "xxx" , "Number" : "3403290"},
"MobileNumber" : { "CustName" : "yyy" , "Number" : "9323304302"}}]
[{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"} , "HomeTown" : "BB" ,
"PhoneNumber" : { "CustName" : "xxx" , "Number" : "3403290"},
"MobileNumber" : { "CustName" : "yyy" , "Number" : "9323304302"}}]
[{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"} , "HomeTown" : "BB" ,
"PhoneNumber" : { "CustName" : "xxx" , "Number" : "3403290"},
"MobileNumber" : { "CustName" : "yyy" , "Number" : "9323304302"}}]
In a collection all doc's have different HomeTown, i just know the key name HomeTown, how can i get the HomeTown values?
In mongo site, i just can find find() and findOne().
Thanks!

find() is enough.
db.CollectionName.find({},{HomeTown:1})
in java, it would be:
BasicDBObject query = new BasicDBObject();
BasicDBObject field = new BasicDBObject();
field.put("HomeTown", 1);
DBCursor cursor = db.getCollection(collectionName).find(query,field);
while (cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
result.add(obj.getString("HomeTown"));
}

db.CollectionName.find({},{HomeTown:1,PhoneNumber:0})
Would be wrong, but
db.CollectionName.find({},{HomeTown:1, _id:0})
would be right, because you need to suppress _id explicitly. Just FYI.

Mongo m = new Mongo('localhost',27017);
DB db = m.getDB("yourDBName");
Collection coll = db.getCollection("yourCollectionName")
BasicDBObject query = new BasicDBObject();
query.put("HomeTown", 1);
DBCursor cursor = coll.find(query);
ArrayList arr = new ArrayList();
String str;
while (cursor.hasNext()) {
str=cursor.curr().get("HomeTown").toString();
arr.add(str);
}

for(int value=0;value<=10;value++)
{
DBCollection tableDetails = db.getCollection("Collection Name");
BasicDBObject queryDetails = new BasicDBObject();
queryDetails.put("_id", value);
DBCursor cursorDetails =tableDetails.find(queryDetails);
DBObject oneDetails;
boolean Name=cursorDetails.hasNext();
while(Name)
{
oneDetails=cursorDetails.next();
String data=oneDetails.get("HomeTown").toString();
System.out.println(data);
}
}

Related

MongoDB : Converting String Field Into Int using JAVA

I am learning mongoDB.I have a collection which looks like this :
{
"_id" : ObjectId("558cf353209c021b5a2fcbe5"),
"term" : "gamma red eye tennis dampener",
"year" : "2015",
"month" : "05",
"day" : "29",
"hour" : "09",
"dayofyear" : "176",
"weekofyear" : "26",
"productcount" : "1",
"count" : "1"
}
{
"_id" : ObjectId("578cf353209c021b5a2fcbe5"),
"term" : "tennis dampener",
"year" : "2015",
"month" : "05",
"day" : "29",
"hour" : "09",
"dayofyear" : "176",
"weekofyear" : "26",
"productcount" : "1",
"count" : "7"
}
{
"_id" : ObjectId("568cf353209c021b5a2fcbe5"),
"term" : "gamma ",
"year" : "2015",
"month" : "05",
"day" : "29",
"hour" : "09",
"dayofyear" : "176",
"weekofyear" : "26",
"productcount" : "1",
"count" : "4"
}
Here the field count is String. I want to iterate through all the documents and convert it into INT using JAVA.
I am able to do it through console using this:
db.tq.find().forEach(function(obj) {
obj.count= NumberInt(obj.count);
db.tq.save(obj);
})
How to do it in java ?
You should do something like this -
DBCollection collection = db.getCollection("collection");
BasicDBObject document = new BasicDBObject();
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
DBObject cur = cursor.next();
String id = cur.get("_id").toString();
String c = cur.get("count").toString();
int updateCount = Integer.parseInt(c); //change to int
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set", new BasicDBObject().append("count", updateCount));
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("_id", new ObjectId(id));
collection.update(searchQuery, updateQuery);
}

Multiple update in mongodb using java

I've this document:
{
"_id" : ObjectId("54140782b6d2ca6018585093"),
"user_id" : ObjectId("53f4ae1ae750619418a20467"),
"date" : ISODate("2014-09-13T08:59:46.709Z"),
"type" : 0,
"tot" : 2,
"additional_info" : {
"item_id" : ObjectId("540986159ef9ebafd3dcb5d0"),
"shop_id" : ObjectId("53f4cc5a6e09f788a103d0a4"),
"ap_id" : ObjectId("53f4cc5a6e09f788a103d0a5")
},
"transactions" : [
{
"_id" : ObjectId("54140782b6d2ca6018585091"),
"date_creation" : ISODate("2014-09-13T08:59:46.711Z"),
"type" : -1
},
{
"_id" : ObjectId("54140782b6d2ca6018585092"),
"date_creation" : ISODate("2014-09-13T08:59:46.788Z"),
"type" : 1
}
]
}
and I need to add 2 more field to the first transaction opbject:
- date_execution: date
- result: this bson document
{ "server_used" : "xxx.xxx.xxx.xxx:27017" , "ok" : 1 , "n" : 1 , "updated_executed" : true} (m_OR.getDocument() in the following code example)
to obtaing that document
{
"_id" : ObjectId("54140811b6d25137753c1a1a"),
"user_id" : ObjectId("53f4ae1ae750619418a20467"),
"date" : ISODate("2014-09-13T09:02:09.098Z"),
"type" : 0,
"tot" : 2,
"additional_info" : {
"item_id" : ObjectId("540986159ef9ebafd3dcb5d0"),
"shop_id" : ObjectId("53f4cc5a6e09f788a103d0a4"),
"ap_id" : ObjectId("53f4cc5a6e09f788a103d0a5")
},
"transactions" : [
{
"_id" : ObjectId("54140811b6d25137753c1a18"),
"date_creation" : ISODate("2014-09-13T09:02:09.100Z"),
"type" : -1,
"result" : {
"server_used" : "xxx.xxx.xxx.xxx:27017",
"ok" : 1,
"n" : 1,
"updated_executed" : true
},
"date_execution" : ISODate("2014-09-13T09:02:15.370Z")
},
{
"_id" : ObjectId("54140811b6d25137753c1a19"),
"date_creation" : ISODate("2014-09-13T09:02:09.179Z"),
"type" : 1
}
]
}
The only way I was able to do that is the do 2 separates updates (update is a my wrapper funciont that execute the real updates in mongodb and it works fine):
// where
BasicDBObject query = new BasicDBObject();
query.append("transactions._id", m_Task.ID());
// new value for result - 1st upd
BasicDBObject value = new BasicDBObject();
value.put("$set",new BasicDBObject("transactions.$.date_execution",new Date()));
update(this._systemDB, "activities", query, value);
// new value for date_execution - 2nd upd
value = new BasicDBObject();
value.put("$set",new BasicDBObject("transactions.$.result",m_OR.getDocument()));
update(this._systemDB, "activities", query, value);
If I try to do this:
BasicDBObject value = new BasicDBObject();
value.put("$set",new BasicDBObject("transactions.$.date_execution",new Date()));
value.put("$set",new BasicDBObject("transactions.$.result",m_OR.getDocument()));
or = update(this._systemDB, "activities", query, value);
just the 2nd set will be applied.
Is there any way do avoid the double execution and apply the update with just one call?
Basic rule of "hash/map" objects is that you can only have one key. It's the "highlander" rule ( "There can be only one" ) applied in general reason. So just apply differently:
BasicDBObject value = new BasicDBObject();
value.put("$set",
new BasicDBObject("transactions.$.date_execution",new Date())
.add( new BasicDBObject("transactions.$.result",m_OR.getDocument() )
);
So basically "both" field arguments are part of the "$set" statement as in the serialized form:
{
"$set": {
"transactions.$.date_execution": new Date(),
"transactions.$.result": m_Or.getDocument()
}
}
Which is basically what you want in the end.
Your suggestion was right, just had to fix a little the syntax this way:
BasicDBObject value = new BasicDBObject();
value.put("$set",
new BasicDBObject("transactions.$.date_execution",new Date())
.append("transactions.$.result",m_OR.getDocument())
);
This worked perfectly ;)
Thanks!
Samuel

MongoDB Query in Array of Arrays and add if not present

I have
{
"Districts" :
[{ "name" : "Krishna"
, "Locations" : [{ "name" : "Vijayawada"}
,{ "name" : "Machilipatnam"}]}
, { "name" : "Guntur"
, "Locations" : [{ "name" : "Satenpalli"}]}
]
, "_id" : 1
, "name" : "Andhra Pradesh"
}
I am trying to create one more Location "Achampet" if District name is "Guntur" so the result should be this below. The result should be the same even if I try to add Achampet more than once.
{
"Districts" :
[{ "name" : "Krishna"
, "Locations" : [{ "name" : "Vijayawada"}
,{ "name" : "Machilipatnam"}]}
, { "name" : "Guntur"
, "Locations" : [{ "name" : "Satenpalli"}
,{ "name" : "Achampet"}]}
]
, "_id" : 1
, "name" : "Andhra Pradesh"
}
But my java code doesn't work
DBObject newLoc = new BasicDBObject("Districts", new BasicDBObject("name", distName).append("Locations", new BasicDBObject("name", locName)));
if (statesColl.findOne(newLoc) == null) {
DBObject updateLoc = new BasicDBObject("$push", newLoc);
statesColl.update(queryDist, updateLoc);
}
It is creating a new District everytime I try to add a location. How can I fix this?
This is how you can do it using the $ positional operator in Java:
...
DBObject selectQuery = new BasicDBObject("_id", 1); // Matches the document
selectQuery.append("Districts.name", distName); // Matches the element in the array where District name = Guntur
BasicDBObject updateFields = new BasicDBObject();
updateFields.put("Districts.$.Locations", new BasicDBObject("name":"Achampet"));
DBObject updateQuery = new BasicDBObject("$addToSet", updateFields);
statesColl.update(selectQuery, updateQuery);
...

remove _id from mongodb result java

My code is
DBCollection collection = db.getCollection("volume");
DBCursor cursor = collection.find();
DBObject resultElement = cursor.next();
Map resultElementMap = resultElement.toMap();
System.out.println(resultElementMap);
And the result is:
{_id=521b509d20954a0aff8d9b02, title={ "text" : "Volume Of Work
Orders" , "x" : -20.0}, xAxis={ "title" : { "text" : "2012 "} ,
"categories" : [ "Jan" , "Feb" , "Mar" , "Apr" , "May" , "Jun" , "Jul"
, "Aug" , "Sep" , "Oct" , "Nov" , "Dec"]}, yAxis={ "min" : 1000.0 ,
"max" : 7000.0 , "title" : { "text" : "Volume(K)"} , "plotLines" : [ {
"label" : { "text" : "Average" , "x" : 25.0} , "color" : "black" ,
"width" : 2.0 , "value" : 30.0 , "dashStyle" : "solid"}]}, legend={
"backgroundColor" : "#FFFFFF" , "reversed" : true}, series=[ { "name"
: "Volume" , "showInLegend" : false , "data" : [ 2909.0 , 3080.0 ,
4851.0 , 3087.0 , 2960.0 , 2911.0 , 1900.0 , 3066.0 , 3029.0 , 5207.0 , 3056.0 , 3057.0]}]}
I need to remove _id from the result. I understand i need to play around with collection.find(), but please can anyone help me? Am not able to get sesired result
Two options:
You can remove the "_id" field from the map created:
...
resultElementMap.remove("_id");
System.out.println(resultElementMap);
Or you can ask the query results to not include the _id field:
DBObject allQuery = new BasicDBObject();
DBObject removeIdProjection = new basicDBObject("_id", 0);
DBCollection collection = db.getCollection("volume");
DBCursor cursor = collection.find(allQuery, removeIdProjection);
DBObject resultElement = cursor.next();
Map resultElementMap = resultElement.toMap();
System.out.println(resultElementMap);
See the documentation on projections for all of the details.
Another option to consider, if you are reading the results iteratively, is doing something like this:
final FindIterable<Document> foundResults = collection.find();
for (final Document doc : foundResults) {
doc.remove("_id");
// doc.toJson() no longer has _id
}

MongoDb accesing nested documents in java

I am new to MongoDB. I am trying to access nested doc in mongodb. My sample doc is
{
"Advertisement" : {
"html" : "zxcxz"
},
"Notification" : {
"date_from" : ISODate("2013-06-30T18:30:00Z"),
"date_too" : ISODate("2013-07-16T18:30:00Z"),
"description" : "vcvc",
"url" : "vcvc"
},
"_id" : ObjectId("51e4f10ee4b08e0a6ebcbe46"),
"group_name" : "sumit",
"target_audience" : {
"gender" : "male",
"section" : "xyz",
"catagory" : "--Computer--",
"location" : {
"country" : "--Country--",
"state" : "--State--",
"city" : "--City--"
}
}
}
I am trying to get gender from target_audience. My java code is
DBCursor f=con.coll.find(query);
while(f.hasNext())
{
f.next();
gender=(String) f.curr().get("target_audience.gender");
}
But it returns null.
The result of DBCursor.next() and DBCursor.curr() is a BasicDBObject. For keys with embedded documents, BasicDBObject.get(key) returns a BasicDBObject
DBCursor f=con.coll.find(query);
while(f.hasNext())
{
BasicDBObject result = (BasicDBObject) f.next();
BasicDBObject target = (BasicDBObject) result.get("target_audience");
gender = (String) target.get("gender");
}

Categories

Resources