MongoDB : Converting String Field Into Int using JAVA - 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);
}

Related

How to get a String inside an Object Array using MongoDB Java?

I'm trying to learn MongoDB and I want to get a String inside an Object Array, my MongoDB document is here:
{
"_id" : ObjectId("5f1507fed91e81246c409a59"),
"identification" : "punishment",
"lastID" : 2,
"punishmentsTypes" : [
{
"category" : "OFENSA_JOGADOR",
"reason" : "Ofensa a Jogador",
"group" : [
"HELPER",
"MODERATOR",
"ADMINISTRATOR",
"MANAGER",
"MASTER"
],
"description" : "Ofender algum jogador",
"cases" : [
{
"1" : {
"type" : "MUTE",
"duration" : 604800000
}
},
{
"2" : {
"type" : "BAN",
"duration" : 0
}
}
]
},
{
"category" : "FALSIFICACAO",
"reason" : "Falsificação de provas",
"group" : [
"ADMINISTRATOR",
"MANAGER",
"MASTER"
],
"description" : "Falsicar provas ao denunciar um jogador em nosso fórum",
"cases" : [
{
"1" : {
"type" : "BAN",
"duration" : 0
}
}
]
},
{
"category" : "HACK",
"reason" : "Hack",
"group" : [
"MODERATOR",
"ADMINISTRATOR",
"MANAGER",
"MASTER"
],
"description" : "Uso de cheats ou programas ilícitos",
"cases" : [
{
"1" : {
"type" : "BAN",
"duration" : 7776000000.0
}
},
{
"2" : {
"type" : "BAN",
"duration" : 0
}
}
]
}
],
"unpunishmentTypes" : [
{}
]
}
I've tried this:
MongoCollection<Document> collection = mongoDatabase.getCollection("settings");
BasicDBObject query = new BasicDBObject();
BasicDBObject field = new BasicDBObject();
query.put("id", "punish");
field.put("punishmentsTypes", 1);
field.put("_id", 0);
Document test = collection.find(query).projection(field).first();
assert test != null;
Object object = test.get("punishmentsTypes");
System.out.println(object);
And that's the output:
[Document{{category=OFENSA_JOGADOR}},
Document{{category=FALSIFICACAO}}, Document{{category=HACK}}]
How can I get only the category string, to the output be: OFENSA_JOGADOR, FALSIFICACAO, HACK?
I'm not sure how did you get that result with your query but here is how I get your result:
MongoCollection<Document> collection = mongoDatabase.getCollection("settings");
Document query = new Document();
query.put("identification", "punishment");
Document test = collection.find(query).first();
List<Document> punishmentsTypes = test.getList("punishmentsTypes", Document.class);
for (Document document : punishmentsTypes) {
String category = document.getString("category");
System.out.println(category);
}

Need to update only particular element in an array of mongo in java

I want to update a particular element in an array of mongo with filters.
I have already tried having using BasicDBObject, but than not able to use filter as i have collection of type MongoCollection.
MongoCollection collection = db.getCollection(tnId);
Even tried:
FindIterable<Document> document = collection.find(new BasicDBObject("DocumentName", documentName) .append("Attributes.name", "Party 1" ).append("Attributes.value", 12) .append("Attributes.actualValue.initialValue", USA));
But in this case What I get is the whole record and than I have to iterate through each Attribute again.
mongo = new MongoClient("localhost", 27017);
MongoDatabase db = mongo.getDatabase(companyName);
MongoCollection collection = db.getCollection(tnId);
Actual data which I am passing is
{
"DocumentName" : "doc1",
"Attributes" : [
{
"name" : "Party 1",
"value" : 12,
"actualValue" : {
"initialValue" : "USA"
}
},
{
"name" : "Party 1",
"value" : 16,
"actualValue" : {
"initialValue" : "SYSTEM"
}
}
]
}
and I want to search attribute where actualValue is "USA" and Value of attribute is 12 and updated data should look like
{
"DocumentName" : "doc1",
"Attributes" : [
{
"name" : "Party 1",
"value" : 12,
"actualValue" : {
"initialValue" : "USA"
},
"updatedvalue" : {
"initialValue" : "USA",
"changedValue" : "Europe"
}
},
{
"name" : "Party 1",
"value" : 16,
"actualValue" : {
"initialValue" : "SYSTEM"
}
}
]
}
db.collection.findOneAndUpdate({ "Attributes.actualValue.initialValue": "USA" },
{ $set: { "Attributes.$.updatedvalue.initialValue": "USA", "Attributes.$.updatedvalue.changedValue": "Europe" } })
db.collection.findOneAndUpdate({ "Attributes.actualValue.initialValue": "USA" },
{ $set: { "Attributes.$.updatedvalue.initialValue": "India", "Attributes.$.updatedvalue.changedValue": "India" } })
Try with this one
db.collection.updateMany(
{ "Attributes.actualValue.initialValue": "USA" },
{ $set: { "Attributes.$.updatedvalue" : {
"initialValue" : "USA",
"changedValue" : "Europe"
} } }
)
How I did is. I made a document where i added teh required data which i want to update it with.Say
Document valueDocument = new Document();
valueDocument.put("InitialValue", USA);
BasicDBObject query = new BasicDBObject();
query.put("Attributes", att);
BasicDBObject data = new BasicDBObject();
data.put("Attributes.$.updatedvalue" + qCLevel, valueDocument);
BasicDBObject command = new BasicDBObject();
command.put("$set", data);
collection.updateOne(query, command);
It goes and insert the data in the right place.

How can we count the number of items in arraylist from different documents in mongodb java?

Assuming I have these documents:
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "blue", "purple" ] }
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ "red", "yellow"] }
The result I would like is
blue : 2
red : 2
black : 1
purple : 1
yellow : 1
Is this possible to perform using the mongodb or do I need to manually implemented after getting colors array in Java? Hints or any help would be of very useful.
This is how I get the database and the collections
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoCollection<Document> collection = mongoClient.getDatabase("tweets")
.getCollection("tweet");
You can try the below aggregation.
db.collection.aggregate({$unwind:"$colors"},{$group: { _id:"$colors",count:{$sum:1} }})
The query will $unwind the array. From the docs
Deconstructs an array field from the input documents to output a
document for each element.
Response after $unwind stage.
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", "colors" : "blue" }
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", "colors" : "black" }
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", "colors" : "red" }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", "colors" : "blue" }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", "colors" : "purple" }
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", "colors" : "red" }
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", "colors" : "yellow" }
Next step is to $group the data on color while using $sum to count the colors
Final Output
{ "_id" : "yellow", "count" : 1 }
{ "_id" : "blue", "count" : 2 }
{ "_id" : "black", "count" : 1 }
{ "_id" : "red", "count" : 2 }
{ "_id" : "purple", "count" : 1 }
Java Update:
3.x Version
collection.aggregate( Arrays.asList(Aggregates.unwind("$colors"), Aggregates.group("$colors", Accumulators.sum("count", 1))));
2.x Version
collection.aggregate( Arrays.asList(new BasicDBObject("$unwind", "$colors"), new BasicDBObject("$group", new BasicDBObject("_id","$colors").append("count",new BasicDBObject("$sum", 1)))));

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

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

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

Categories

Resources