Update multiples fields Mongo DB - java

i have a big problem with mongo db because i want to update a multiple fields with One request.
My Json is :
db.test.findOne();
{
"_id" : ObjectId("51e7dd16d2f8db27b56ea282"),
"ad" : "noc2",
"list" : {
"p45" : {
"id" : "p45",
"date" : ISODate("2014-01-01T12:18:30.568Z"),
"value3" : 21,
"value1" : 100,
"value2" : 489
},
"p6" : {
"id" : "p6"
"date" : ISODate("2013-07-18T12:18:30.568Z"),
"value3" : 21,
"value1" : 100,
"value2" : 489
},
"p4578" : {
"id" : "4578"
"date" : ISODate("2013-07-18T12:18:30.568Z"),
"value3" : 21,
"value1" : 100,
"value2" : 489
}
}
}
I want created a field createdDate for all elements list , if createdDate field doesn't exist or is null.
A request example, what i use for update one field with upsert true in my code java :
db.people.update({"advertiser":"noc2","list.4578.createdDate":{$exists:false}},{$set:{"list.p4578.createdDate":"08/08/08"}});
I tried with java where list.4578 is replaced by variable but is too long for too much fields. If i have 100 fields, i do execute 100 requests.
Look :
public void createdFirstDateField(MongoAccess mongo, String ad,HashMap<String,Object> hfirstDate){
BasicDBObject searchQuery = new BasicDBObject();
Iterator <String> it = hfirstDate.keySet().iterator();
String key="";
while (it.hasNext()){
key=it.next();
searchQuery.append("ad", ad).append(key, new BasicDBObject("$exists", false));
//System.out.println(key);
BasicDBObject doc = new BasicDBObject ();
doc.append("$set",new BasicDBObject(key,new Date()));
mongo.insert(searchQuery, doc); // update with upsert true
}
}
Thanks.

Why don't you use the update with upsert?
db.people.update({"advertiser": "noc2"},
{$set: {"list.$.createdDate": "08/08/08"}},
{$upsert: true);
If the createdDate exists it will be updated, if not it will be inserted.

You can update multiple documents at once, using update Multi. But there in not atomic way to update multiple embedded documents.
You can checkout mongodb positional operator, but this does not fit in your use case.

Related

Retrieve all the documents matching the criteria in an array elements which is a subdocument

{
"_id" : ObjectId("577b54816081dd32cd3e2d60"),
"user" : ObjectId("577b54816081dd32cd3e2d5e"),
"journals" : [
{
"title" : "Journal Title2",
"desc" : "desx2",
"feeling" : 3,
"date" : ISODate("2016-07-05T06:32:45.404Z"),
"deleteFl" : true,
"_id" : ObjectId("577b548d6081dd32cd3e2d64")
},
{
"title" : "Journal Title3",
"desc" : "desx3",
"feeling" : 3,
"date" : ISODate("2016-07-05T06:49:00.156Z"),
"deleteFl" : false,
"_id" : ObjectId("577b585c6081dd32cd3e2d6d")
},
{
"title" : "Journal Title4",
"desc" : "desx4",
"feeling" : 3,
"date" : ISODate("2016-07-05T06:49:06.700Z"),
"deleteFl" : false,
"_id" : ObjectId("577b58626081dd32cd3e2d70")
}
]
}
Above is my document structure
now, I need all the journal documents whose deleteFl = false.
I tried in this way using Java Mongo driver
getDatabase().getCollection("journals").find(and(eq("user", user), eq("journals.deleteFl", false)));
but still it gives me back all the documents including "deleteFl": true. any help here ?
Actually, your query returns 1 document, because the data is inside 1 document. What you want is to limit the returning fields of a document (limit subdocuments).
Note: You can do that using elemMatch in the projection, to limit the fields returned by the query. But elemMatch will return just one subdocument. (I posted a deleted wrong answer using elemMatch)
When you want all subdocuments and only specific subdocuments from inside an array, you need to use the aggregation pipeline.
Here is a tested code that does what you want (just change DB and colelction name):
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection collection = db.getCollection("test");
Iterable<Document> output = collection.aggregate(asList(
new BasicDBObject("$unwind", "$journals"),
new BasicDBObject("$match", new BasicDBObject("journals.deleteFl", false))
));
for (Document dbObject : output)
{
System.out.println(dbObject);
}

How to get and update nested document in mongo db using java

I have a documents in mongo db as follows. I want to get and update the document having policyMap equals CostCalculation.In this CostCalculation has array format update in array elements such as 'policyName' have 'CostCalculationPolicyuserDefine' and set 'policyDes' = 'New Value' Please suggest the java code to solve this.
I searched mongo operartors but couldn't get it.
Sample mongo db document structure.
{
"policyMap" : {
"CostCalculation" : [{
"policyName" : "CostCalculationPolicyuserDefine",
"policyDesc" : "Priority user Defined Policy",
"userDefined" : 1
},
{
"policyName" : "CostCalculationPolicyuserDefine1",
"policyDesc" : "Priority user Defined Policy",
"userDefined" : 1
}]
},
"bsVer" : 2,
"bsFlag" : true,
"crBy" : "xxxxx",
"crDate" : NumberLong("1440138385345"),
"entNm" : "xxxx"
}
{
"policyMap" : {
"CostValue" : [{
"policyName" : "CostValuePolicyuserDefine",
"policyDesc" : "Priority user Defined Policy",
"userDefined" : 1
},
{
"policyName" : "CostCalculationPolicyuserDefine1",
"policyDesc" : "Priority user Defined Policy",
"userDefined" : 1
}]
},
"bsVer" : 2,
"bsFlag" : true,
"crBy" : "xxxxx",
"crDate" : NumberLong("1440138385345"),
"entNm" : "xxxx"
}
My sample java code
DBCollection coll = db.getCollection("nestedtest");
BasicDBObject searchDocument = new BasicDBObject();
searchDocument.put( "policyMap ", new BasicDBObject("$exists", new BasicDBObject("$eq", "CostCalculation")));
coll.remove(searchDocument);
What would be the similar java code to get the correct result.
Thanks.
This code works using Mongo 3 java drivers. It removes the need for all the BasicDBObjects that are in your code:
MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017");
MongoClient client = new MongoClient(uri);
initialiseCollection(client);
Bson filter = Filters.exists("policyMap.costCalculation");
client.getDatabase("test").getCollection("test").deleteOne(filter);
DBCollection coll = db.getCollection("minnalPolicyMetadata");
BasicDBObject searchDocument = new BasicDBObject();
searchDocument.put("policyMap.CostCalculation",new BasicDBObject("$exists",true));
DBCursor cursor = coll.find(searchDocument);
if(cursor.count() != 0){
while(cursor.hasNext())
System.out.println(cursor.next());
}
In this way i solved this problem.Use exists operator in mongo

Updating Nested Embedded Documents in mongodb

I am new to mongodb. Plz help me with this.
I need a document like this
employee{
_id:111,
name:xxx,
dependents : [ {
name:a,
age:51,
dep_children:[{name:aa}{name:bb}{name:c}]
}
{
name:b,
age:52,
dep_children:[{name:aa}{name:bb}{name:c}]
}
{
name:c,
age:51,
dep_children:[{name:aa}{name:bb}{name:cc}]
}
]
}
I am using the below script to migrate data for SQL and update it into mongoDB
My code looks something like this:
while(personcount>=0)
{
BasicDBObject doc = new BasicDBObject("_id",ind1.get(count)).
append("name",ind2.get(count));
coll.insert(doc);
while(dependentcount>0)
{
BasicDBObject querymongo = new BasicDBObject();
querymongo.put( "name",ind.get(count));
BasicDBObject tenant = new BasicDBObject();
tenant.put("name",indsa.get(innercount) );
tenant.put("age", indsa2.get(innercount));
BasicDBObject update = new BasicDBObject();
update.put("$push", new BasicDBObject("dependents",tenant));
coll.update(querymongo, update,true,true);
while(kidcount>0)
{
BasicDBObject querymongofact = new BasicDBObject();
querymongokid.put( "dependent.name",indsa.get(innercount));
BasicDBObject tenantkid = new BasicDBObject();
tenantkid .put("name",indfact.get(innercountfact) );
BasicDBObject updatekid = new BasicDBObject();
updatekid .put("$push", new BasicDBObject("dependent.dep_children",tenantkid));
coll.update(querymongokid, updatekid ,true,true);
}
}
}
when we print querymongokid and updatekid, the data inside it are expected values itself. This code is not throwing any error. But in data base the only dep_children data is not getting updated . I am not getting wt went wrong. please help me
Thanks in advance
Your last query fails in the mongo driver in a sense that the update has no effect - but it's not an actual error. Just let me reproduce what you are doing in the mongo shell:
> db.coll.insert({_id:1,name:"name1"})
> db.coll.update({name:"name1"}, {"$push": {dependents: {name:"a", age:50}}})
> db.coll.update({name:"name1"}, {"$push": {dependents: {name:"b", age:55}}})
> db.coll.findOne()
{
"_id" : 1,
"dependents" : [
{
"name" : "a",
"age" : 50
},
{
"name" : "b",
"age" : 55
}
],
"name" : "name1"
}
> db.coll.update({"dependents.name": "a"}, {"$push": {"dependents.dep_children": {name:"aa"}}})
can't append to array using string field name: dep_children
> db.coll.update({"dependents.name": "a"}, {"$push": {"dependents.$.dep_children": {name:"aa"}}})
> db.coll.findOne()
{
"_id" : 1,
"dependents" : [
{
"age" : 50,
"dep_children" : [
{
"name" : "aa"
}
],
"name" : "a"
},
{
"name" : "b",
"age" : 55
}
],
"name" : "name1"
}
Unfortunately, I have very little experience with the native mongo java driver (I'm usually on Spring data), but changing your line
updatekid.put("$push", new BasicDBObject("dependent.dep_children",tenantkid));
to
updatekid.put("$push", new BasicDBObject("dependent.$.dep_children",tenantkid));
should do the trick as well.
The reason for that behavior is that "dependent.dep_children" is not a valid selector as it corresponds to "go to field dep_children within the subdocument dependent". However, "dependent" happens to be an array without any fields. The $ replaces an explicit index and will make sure the correct subdocument from your query is selected.
Also see here for a less error-prone formulation of your query - without using $elemMatch it will only work if your query uniquely identifies a certain array element. With $elemMatch it will always work, but only update the first match.

BasicDBObject update duplicate same document

I have a big problem with the api java mongodb. I use a request with the update methods of DBCollection class and in the mongodb i get a multiple same document while the value doesn't change,help me please. I don't want to have a duplicate document.
BasicDBObject query = new BasicDBObject();
query.append("ad", "man2ist").append("list.id", new BasicDBObject("$ne", "5")); // "list.id" : {$ne : 0 }
BasicDBObject a = new BasicDBObject("id",String.valueOf(5)).append("value", 100);
BasicDBObject upd = new BasicDBObject("$addToSet",new BasicDBObject("list",a));
System.out.println(query);
System.out.println(upd);
WriteResult r = dbc.update(query,upd,true,false);
//db.friends.update({ "ad" : "man2ist" , "list.id" : { $ne : "4"} },{ $addToSet : { "list" : { "id" : "4","value" : 100}}},true,true);
my document here :
{
"ad" : "man2ist",
"createdDate" : ISODate(),
"list" : [
{
"id" : "45",
"value" : 489
},
{
"id" : "5",
"value" : 20,
},
{
"id" : "4578",
"value" : 21,
} ]}
The problem is that you set the upset flag to true, meaning that the document should be created if no document matching the criteria is found. If there is no document matching the criteria in the db, the mongo shell will do the same.
If you change your query to this,
WriteResult r = dbc.update(query,upd,false,false);
it should work all the time.

How to acces mongodb collection through aggregate function (like group, count and distinct) through java driver?

Here is my mongdb Collection:
{ "_id" : ObjectId("50033fb1ecc250aa369a678a"), "ID" : 1, "FirstName" : "ijaz",
"LastName" : "alam", "Age" : 21, "Address" : "peshawer" }
{ "_id" : ObjectId("50033fc2ecc250aa369a678b"), "ID" : 2, "FirstName" : "ashfaq"
,"LastName" : "khan", "Age" : 1921, "Address" : "sadkabad" }
{ "_id" : ObjectId("50033fdeecc250aa369a678c"), "ID" : 3, "FirstName" : "danyal"
,"LastName" : "alam", "Age" : 18, "Address" : "lahore" }
{ "_id" : ObjectId("50033ff7ecc250aa369a678d"), "ID" : 43, "FirstName" : "shahzad"
, "LastName" : "sad", "Age" : 22, "Address" : "nazirabad" }
Now i want to use aggregate function like group,distinct and count on above collection through java driver or how to implement aggregate functions in query through java driver.
Distinct and count and special Mongo commands, you don't need to do any special aggregation to use those. Just call them with the appropriate parameters on you DBCollection instances.
myCollection.distinct("Age") // gives you all the ages in the collection
myCollection.count(new BasicDBObject("Age", 22)) // gives you a count of 22 year olds
For other aggregation operations, you want the Java GroupCommand:
new GroupCommand(myCollection,
new BasicDBObject("Age ", true),
null,
new BasicDBObject("count", 0),
"function(key,val){ val.count++;}",
null); //gives counts of each age in the collection
If you're running on the 2.1.x development release of Mongo or later, check out the aggregation framework. It's better than the existing group command (but not yet production ready at the time of this answer).

Categories