Reputation: 16122
I have a MongoDB collection of companies
and models
in following format:
[{company:'Any company', models:['Model1','model2','model3']},
...
{company:'Any-company', models:['model83','Model-abc','MODEL43']}]
As you can see some of company
or model
names are upper case or written with dash symbol.
I want to save this collection into variable, and I need it to be Lower Case and without dashes.
I did it with just mongoose find
and for loop
like so:
mongoose.model('Company', companySchema).find({}, function(err, docs) {
if (err) {
console.log(err);
} else {
var companyLowerCase = docs;
for(var i=0;i<companyLowerCase.length;i++) {
companyLowerCase[i].company = companyLowerCase[i].company.replace(/-/g, " ").toLowerCase();
for(var j=0;j<companyLowerCase[i].models.length;j++) {
companyLowerCase[i].models[j] = companyLowerCase[i].models[j].replace(/-/g, " ").toLowerCase();
}
}
}
});
But I'm wondering if it is possible to achieve with MongoDB. I found that you can lower case you values like so:
db.inventory.aggregate([{
$project:
{
item: { $toLower: "$item" },
description: { $toLower: "$description" }
}
}]);
But can you replace "-"
on " "
with MongoDB? If you can, then what request should I send to the MongoDB to achieve my goal?
NOTE: Collection in database should not change. Modification must be only save in variable.
Upvotes: 0
Views: 86
Reputation: 5322
I don't think you can since MongoDB doesn't have a replace operator for $project
Upvotes: 2