Update same field in multiple documents with data from json - json

I have a MongoDB looking like this:
[
{
"status" : 0,
"name" : "Yaknow",
"email" : "yaknow#not.this",
"_id" : "5875a42ea469f40c684de385"
},
{
"status" : 1,
"name" : "johnk",
"email" : "johnk#not#this",
"_id" : "586e31c6ce07af6f891f80fd"
}
]
Meanwhile, all the emails have changed and I got a Json with the new ones:
[
{
"email" : "yaknow#gmai.new",
"_id" : "5875a42ea469f40c684de385"
},
{
"email" : "johnk#gmail.new",
"_id" : "586e31c6ce07af6f891f80fd"
}
]
How do I update all the emails?

There is no operator in mongodb which allows you modify string value by replacing some part of string. You should get documents, and then for each of documents you should locally prepare updated value and update document:
db.collection.find({}).forEach(function(doc){
var newEmail = doc.email.substr(0, doc.email.indexOf('#')) + "#gmail.new";
db.collection.update({_id: doc._id}, {$set:{email: newEmail}});
});

Related

How to push new key and value in JSON array in mongodb?

How can I push new key and value in JSON array?
I tried I used push keyword in update query but I got a different output. I used:
db.users.updateOne({"name":"viki"},{$push{"address.district":"thambaram"}})
I have this document:
{ "_id" : ObjectId("58934f10c7592b1494fd9a4d"), "name" : "viki", "age" : 100, "subject" : [ "c", "node.js", "java" ], "address" : { "city" : "chennai", "state" : "tamilnadu", "pincode" : "123" } }
I want to add "district":"thambaram" in address json array
I need like:
{ "_id" : ObjectId("58934f10c7592b1494fd9a4d"), "name" : "viki", "age" : 100, "subject" : [ "c", "node.js", "java" ], "address" : { "city" : "chennai", "state" : "tamilnadu", "pincode" : "123","district":"thambaram"} }
Use $set
db.users.updateOne({"name":"viki"},{$set:{"address.district":"thambaram"}})
This should work.
The $push operator appends a specified value to an array. In your case you should use $set

Update a document in an array in MongoDB using webMethods

I have a requirement to a particular document in the arrayList, the sample JSON string for that is
{
"_id" : ObjectId("58b9339502be203f6b476664"),
"_docType" : "Test",
"type" : "mongoUpdate",
"createdDateTime" : "2017-03-03 09:12:53.080",
"contacts" : [
{
"firstName" : "FirstName",
"lastName" : "LastName",
"email" : "someName#email.com",
"contactType" : "Business.",
"phoneNumber" : "1234567890",
"createdDateTime" : "2017-03-03 09:13:04.229",
"lastModifiedDTM" : "2017-03-03 09:13:04.229",
},
{
"firstName" : "FirstName2",
"lastName" : "LastName2",
"email" : "someName#email.com2",
"contactType" : "Business2.",
"phoneNumber" : "1234567890",
"createdDateTime" : "2017-03-03 09:13:04.229",
"lastModifiedDTM" : "2017-03-03 09:13:04.229",
},
{
"firstName" : "FirstName3",
"lastName" : "LastName3",
"email" : "someName#email.com3",
"contactType" : "Business.3",
"phoneNumber" : "12345678903",
"createdDateTime" : "2017-03-03 09:13:04.229",
"lastModifiedDTM" : "2017-03-03 09:13:04.229",
}
]
}
Say I have to update one of the occurrence in the above json.
I have used the $set operation to update the above array and when I see the content in the mongo db I see the the whole array is replaced by single occurrence of contact.
the update command which I have used is
{$set:{"contacts":[{"firstName":"test0103)12","lastName":"test0103","email":"test0103","contactType":"test0103","phoneNumber":"test0103","createdDateTime":"test0103"}]}}
after executing this I see that the whole array list of 3 is replaced with the single instance of contacts.
and at the end I have the output as
"contacts" : [
{
"firstName" : "test0103)12",
"lastName" : "test0103",
"email" : "test0103",
"contactType" : "test0103",
"phoneNumber" : "test0103",
"createdDateTime" : "test0103"
}]
Here is the sample code
First find the document using _id. here collection I took is user
` User.findOne({'_id': 58b9339502be203f6b476664},(err,res) => {
if(res.contacts.length > 0){
var contacts = res.contacts;
var contactsList = [];
var contactobject = {};
// suppose you want to update the contact with firstname - FirstName2
contacts.map((contact,key)=>{
if(contact.firstName == "firstName2"{
contactobject.firstName = "Your updated name";
contactobject.lastName = "Your updated name";
// similary all values you want to update
// Then push to an array after updating new data
contactsList.push(contactObject);
}
else {
// if not the required contact to update
// simply push
contactsList.push(contact);
}
})
// After the map function , now update the new contacts
User.update({email:email},
{$set:{contacts: contactsList}},(err,result) => {
User.findOne({'_id':res._id}).then(updateuser => {
resolve(updateuser);
})
})
}
}) `
Try this , It works

How to compare API request JSON with existing json document in MongoDb?

The title of the question is self explanatory. I want to know what differences are there in JSON Document A which comes from API request and JSON Document B which is already in Mongo DB.how to get changes column name and data also.. i am creating log..that's why i want...
Below is the code of what I'm trying:
NodeJS APICode//
function Updatejob(req, res) {
return function (jobSchedule) {
var obj = new Date();
CompareJSON(req, mongodbjson);
return Job.create(req.body).then(.....)
}
Already Data in Mongodb before Update Record
{
"_id" : ObjectId("586d1032aef194155028e9c7"),
"history" : [
{
"_id" : ObjectId("586d1032aef194155028e9c4"),
"updated_by" : "",
"details" : "Job Created",
"changetype" : "Created",
"datetime" : ISODate("2017-01-04T15:09:38.465Z")
}
],
"current_status" : "Pending",
"time" : 0
}
//REQUEST FOR UPDATE DATA
{
"_id" : ObjectId("586d1032aef194155028e9c7"),
"history" : [
{
"_id" : ObjectId("586d1032aef194155028e9c4"),
"updated_by" : "",
"details" : "Job Completed",
"changetype" : "Completed",
"datetime" : ISODate("2017-01-04T15:09:38.465Z")
}
],
"current_status" : "Completed",
"time" : 0
}
You can use jsondiffpatch:
var delta = jsondiffpatch.diff(object1, object2);
See:
https://www.npmjs.com/package/jsondiffpatch

How to update a nested array value in mongodb?

I want update a array value that is nested within an array value: i.e. set
status = enabled
where alerts.id = 2
{
"_id" : ObjectId("5496a8ed49847b6cd7c7b350"),
"name" : "joe",
"locations" : [
{
"name": "my location",
"alerts" : [
{
"id" : 1,
"status" : null
},
{
"id" : 2,
"status" : null
}
]
}
]
}
I would have used the position $ character, but cannot use it twice in a statement - multi positional operators are not supported yet: https://jira.mongodb.org/browse/SERVER-831
How do I issue a statement to only update the status field of an alert matching an id of 2?
UPDATE
If I change the schema as follows:
{
"_id" : ObjectId("5496ab2149847b6cd7c7b352"),
"name" : "joe",
"locations" : {
"my location" : {
"alerts" : [
{
"id" : 1,
"status" : "enabled"
},
{
"id" : 2,
"status" : "enabled"
}
]
},
"my other location" : {
"alerts" : [
{
"id" : 3,
"status" : null
},
{
"id" : 4,
"status" : null
}
]
}
}
}
I can then use:
update({"locations.my location.alerts.id":1},{$set: {"locations.my location.alerts.$.status": "enabled"}});
Problem is I cannot create indexes on the alert id :-(
it may be better of modelled as such, specially if an index on location and,or alerts.id is needed.
{
"_id" : ObjectId("5496a8ed49847b6cd7c7b350"),
"name" : "joe",
"location" : "myLocation",
"alerts" : [{
"id" : 1,
"status" : null
},
{
"id" : 2,
"status" : null
}
]
}
{
"_id" : ObjectId("5496a8ed49847b6cd7c7b350"),
"name" : "joe",
"location" : "otherLocation",
"alerts" : [{
"id" : 1,
"status" : null
},
{
"id" : 2,
"status" : null
}
]
}
I think you are having a wrong tool for the job. What you have in your example is relational data and it's much easier to handle with relational database. So I would suggest to use SQL-database instead of mongo.
But if you really want to do it with mongo, then I guess the only option is to fetch the document and modify it and put it back.

How to add Timestamp to Spring-Data-Mongo in Roo?

I have a Spring Roo project I am trying to create based on log4mongo-java appender and I want to get access to the data entries that looks like:
{
"_id" : ObjectId("4f16cd30b138685057c8ebcb"),
"timestamp" : ISODate("2012-01-18T13:46:24.704Z"),
"level" : "INFO", "thread" : "catalina-exec-8180-3",
"message" : "method execution[execution(TerminationComponent.terminateCall(..))]",
"loggerName" :
{ "fullyQualifiedClassName" : "component_logger",
"package" : ["component_logger"],
"className" : "component_logger"
},
"properties" : {
"cookieId" : "EDE44DC03EB65D91657885A34C80595E"
},
"fileName" : "LoggingAspect.java",
"method" : "logForComponent",
"lineNumber" : "81", "class" : {
"fullyQualifiedClassName" : "com.comcast.ivr.core.aspects.LoggingAspect",
"package" : ["com", "comcast", "ivr", "core", "aspects", "LoggingAspect"],
"className" : "LoggingAspect"
},
"host" : {
"process" : "2220#pacdcivrqaapp01",
"name" : "pacdcivrqaapp01",
"ip" : "24.40.31.85"
},
"applicationName" : "D2",
"eventType" : "Development"
}
The timestamp looks like:
"timestamp" : ISODate("2012-01-17T22:30:19.839Z")
How can I add a field in my Logging domain object to map this field?
That's just the JavaScript Date (according to the mongo docs, and as can be demonstrated in the shell), so try with java.util.Date.