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
Related
This is the JSON content I have uploaded in Firebase database.
Now I need to access this in my Angular 2 app.
I am getting undefined and NaN while trying to access the objects.
{
"clients" : {
"clients" : {
"-Kdl_wRRkn7nJxgz4B54" : {
"balance" : "100.00",
"email" : "jdoe#gmail.com",
"firstName" : "John",
"lastName" : "Doe",
"phone" : "555-555-5555"
},
"-KdleehAQm0HgVFYdkUo" : {
"balance" : "350.00",
"email" : "stevesmith#gmail.com",
"firstName" : "Steve",
"lastName" : "Smith",
"phone" : "444-444-4444"
}
}
}
}
I am trying to access this here
export class ClientsComponent implements OnInit {
clients:any[];
totalOwed:number;
constructor(
public clientService:ClientService
) { }
ngOnInit() {
this.clientService.getClients().subscribe(clients => {
this.clients = clients;
console.log(this.clients);
this.getTotalOwed();
});
}
getTotalOwed(){
let total = 0;
for(let i = 0;i < this.clients.length;i++){
console.log(this.clients[i]);
total += parseFloat(this.clients[i].balance);
}
this.totalOwed = total;
console.log(this.totalOwed);
}
}
First off, you should re-structure your JSON, the structure below will be better for looping through, and a better practice. second, the reason you are getting not a number is because you are not accessing the balance key's value.
your code to loop through the data structure below would look something like:
for(let i = 0; i < this.clients.length(); i++) {
console.log(this.clients[i].balance)
}
and the JSON:
{
"clients" : [
{
"id" : "-Kdl_wRRkn7nJxgz4B54",
"balance" : "100.00",
"email" : "jdoe#gmail.com",
"firstName" : "John",
"lastName" : "Doe",
"phone" : "555-555-5555"
},
{
"id" : "-KdleehAQm0HgVFYdkUo",
"balance" : "350.00",
"email" : "stevesmith#gmail.com",
"firstName" : "Steve",
"lastName" : "Smith",
"phone" : "444-444-4444"
}
]
}
I have three Post in my collection of three different User
I am trying to fetch the post in my Views Session (Html, Css) Part
But I need to filter the other two post Posted from other two User
because I have some block functionality in my View Section. So all post are
allowed but the user I have blocked her/his post not visible to me and mine to him.
BlockedByUser : (This is my Post Json Data)
{
"_id" : ObjectId("591729b52bb30a19afc9b89d"),
"createdTime" : ISODate("2017-05-13T15:43:49.381Z"),
"isDeleted" : false,
"Message" : "Message Two",
"postedBy" : ObjectId("598adbefb3bf0b85f92edc3b"),
"recipient" : [
ObjectId("598ae453b3bf0b85f92ee331"),
ObjectId("5910691ae2bcdeab80e875f0")
],
"updatedTime" : ISODate("2017-05-20T09:24:39.124Z")
}
Below two user Post Data that I have blocked And
In his recipient Array Key stores my Id recipient [598adbefb3bf0b85f92edc3b]
Block User One :
{
"_id" : ObjectId("591729b52bb30a19afc9b89d"),
"createdTime" : ISODate("2017-05-13T15:43:49.381Z"),
"isDeleted" : false,
"Message" : "Message One",
"postedBy" : ObjectId("598ae453b3bf0b85f92ee331"),
"recipient" : [
ObjectId("598adbefb3bf0b85f92edc3b"),
ObjectId("5910691ae2bcdeab80e875f0"),
ObjectId("598ac93cb3bf0b85f92ece44"),
],
"updatedTime" : ISODate("2017-05-20T09:24:39.124Z")
}
Same as above
Block User Two :
{
"_id" : ObjectId("591729b52bb30a19afc9b89d"),
"createdTime" : ISODate("2017-05-13T15:43:49.381Z"),
"isDeleted" : false,
"Message" : "Message One",
"postedBy" : ObjectId("598ac93cb3bf0b85f92ece44"),
"recipient" : [
ObjectId("598adbefb3bf0b85f92edc3b"),
ObjectId("5910691ae2bcdeab80e875f0"),
ObjectId("598ae453b3bf0b85f92ee331")
],
"updatedTime" : ISODate("2017-05-20T09:24:39.124Z")
}
This is Block Collection that I have created and two blocked user Id with blockUserId key
Block Details One :
{
"_id" : ObjectId("598da2f0b88b0c2b0c735234"),
"blockUserId" : ObjectId("598ae453b3bf0b85f92ee331"),
"blockById" : ObjectId("598adbefb3bf0b85f92edc3b"),
"updatedDate" : ISODate("2017-08-11T12:28:32.145Z"),
"createdDate" : ISODate("2017-08-11T12:28:32.145Z"),
"isBlock" : "true",
"__v" : 0
Block Details Two
{
"_id" : ObjectId("598da558b88b0c2b0c735236"),
"blockUserId" : ObjectId("598ac93cb3bf0b85f92ece44"),
"blockById" : ObjectId("598adbefb3bf0b85f92edc3b"),
"updatedDate" : ISODate("2017-08-11T12:38:48.772Z"),
"createdDate" : ISODate("2017-08-11T12:38:48.772Z"),
"isBlock" : "true",
"__v" : 0
}
I have fetch these blocked collection and store two user blockUserId id in array
arrOne = ["598ae453b3bf0b85f92ee331", "598ac93cb3bf0b85f92ece44"]
And i am applying this query in mongoose db:
query = {$or: [{$and: [{ $or: [{ postedBy: req.params.id},
{recipient: req.params.id}
]
}, { createdTime: { $gt: endTime, $lt: startTime } }
]},{postedBy: {$ne: arrOne}}
]
};
}
But it will return undefined value
I am trying to fetch only my Post or Other user Post that not Blocked my Me, And Blocked User Post will not visible to me
I have to Implement where clause and it works
var query = { $and: [{ $or: [{ postedBy: req.params.id }, { recipient: req.params.id }] }, { "createdTime": { $gt: endTime, "$lt": startTime } }] };
CollectionName.find(query).where('postedBy').nin(blocklist).exec(function(err, response);
Below is my json string in MongoDB i want to delete MasterColors Array on MasterColorGuid in Asp.net Core
{
"_id" : ObjectId("595657a00c1ac702f6e4f5cb"),
"IsActive" : true,
"IPAddress" : null,
"CreatedBy" : "46F5C2E8-83F4-4062-8CD7-1B567B303919",
"CreatedDateUtc" : ISODate("2017-06-30T13:51:38.324Z"),
"ModifiedBy" : "46F5C2E8-83F4-4062-8CD7-1B567B303919",
"ModifiedDateUtc" : ISODate("2017-06-30T13:51:38.324Z"),
"WebSiteGuid" : "12E36FB8-D1B5-4172-8144-1176C0AFA82D",
"ProductGuid" : "8D647BE5-8ABC-4AD8-8342-1254C8096DC8",
"ProductName" : "BuiltĀ® Netbook & Laptop Sleeve 9-10\"",
"ProductCode" : "BT-5603",
"MasterColors" : [
{
"MasterColorGuid" : "49e35057-39a6-4772-93c9-fc10aa87eff8",
"SkuGuid" : "C634041D-116E-447A-A806-9CA04E4DA5B4"
},
{
"MasterColorGuid" : "8ae4d05e-96f4-486d-9a2f-b1535f711f9f",
"SkuGuid" : "04A03C81-07BC-4609-9311-C051784B1502"
}
]
}
var collection = _Productcontext.GetCollection(Collection);
var distinct = collection
.Distinct(new StringFieldDefinition("ProductSKUs.VariantName"), filterSelect)
.ToList();
return distinct;
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}});
});
the response is like the following format
{
"human_man" :
[
{"id" : "12345", "value" : "4567"},
{ "id" : "0000", "value" : "qwer"}
],
"human_woman" :
[
{"id" : "5454", "value" : "6565"},
{ "id" : "7878", "value" : "884"}
],
............................................
}
I want to catch the response for all matches , meaning....
if I use,
response.human_man ::: i would be catching--> [ {"id" : "12345", "value" : "4567"}, { "id" : "0000", "value" : "qwer"}]
if I use,
response.human_woman ::: i would be catching--> [{"id" : "5454", "value" : "6565"}, { "id" : "7878", "value" : "884"}]
so I want to know how to catch the response the type is
response.human_* (it should catch response.human_man & response.human_woman)
hope you guys understood the question.. :)
fast replies would be appreciated
Try this :)
var object = {
"human_man" :
[
{"id" : "12345", "value" : "4567"},
{ "id" : "0000", "value" : "qwer"}
],
"human_woman" :
[
{"id" : "5454", "value" : "6565"},
{ "id" : "7878", "value" : "884"}
]
};
for(var key in object) {
if(/^human_/.test(key))
console.log(object[key]);
}