hie i am new to mongodb, iam trying to replace the commas, in my collection i have plenty of objects
{
"name":"Mobile",
"ProCategories":[
{
"title":"Home,-electronics"
}
]
}
like above there are somany objects in my collection, now i want to remove the commas to all ProCategories array in all objects.
iam trying this using a js file in mongo shell like below
db.companies.find().skip(0).limit(100).forEach(function (doc) {
var replacedTitle = doc.ProCat.filter(function (catTitle) {
return catTitle.title.replace(',', "");
})
db.companies.update({
_id: doc._id
}, {
$set: {
"ProCat": [{
"title": replacedTitle
}]
}
});
})
now in my mongo shell i am doing like this
load("url\\to\\my js file\\path")
i tried in different ways but it is not working Thanks in advance
var replacedTitles = doc.ProCat.map(function (catTitle) {
return { title: catTitle.title.replace(/,/g, "") };
})
filter
removes elements in an array that do not match a condition. This is not what you want to do. Instead, map
applies a function to each element of the array, which is what you want to do. Additionally, you need to wrap each replaced string in an object since you want an array of objects, not an array of strings. The /,/g
makes it so that every comma is removed, not just the first one. The rest should be modified like this.
db.companies.update({
_id: doc._id
}, {
$set: {
"ProCat": replacedTitles,
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.