here's my document:
{
"_id": {
"$oid": "5eb5f0a9d985888edb0523b0"
},
"subs": [{
"name": "list1",
"count": "0"
}, {
"name": "list2",
"count": "0"
}, {
"name": "list3",
"count": "0"
}, {
"name": "list4",
"count": "0"
}]
}
I'm using mongojs currently. I'd like to be able to for instance, find "list2" and increment the count associated with it. I have tried all day and can't seem to figure it out.
any help or direction would be greatly appreciated!
-
I think is using array filters: docs.mongodb.com/manual/reference/command/update/… - stackoverflow.com/questions/51605347/…fedeteka– fedeteka2020年05月09日 00:24:17 +00:00Commented May 9, 2020 at 0:24
-
1is you try to update the values only using mongojs provided functions or just need to update those values by using javascript functions?Aravinda Meewalaarachchi– Aravinda Meewalaarachchi2020年05月09日 01:41:32 +00:00Commented May 9, 2020 at 1:41
-
Can you show us what you've tried ? And as @AravindaMeewalaarachchi pointed do you want a raw mongodb query or you want to use the library ?Mickael B.– Mickael B.2020年05月09日 01:43:31 +00:00Commented May 9, 2020 at 1:43
2 Answers 2
I hope this will help you. I have use programmatic approach to solve your problem.
let payload = {
"_id": {
"$oid": "5eb5f0a9d985888edb0523b0"
},
"subs": [{
"name": "list1",
"count": "0"
}, {
"name": "list2",
"count": "0"
}, {
"name": "list3",
"count": "0"
}, {
"name": "list4",
"count": "0"
}]
}
let fields = ["list2","list4"];
fields.forEach((element)=>{
for(let i=0; i<payload.subs.length; i++){
if(element===payload.subs[i]["name"]){
let value = parseInt(payload.subs[i]["count"]);
payload.subs[i]["count"] = (++value).toString();
}
}
})
console.log(payload.subs)
answered May 9, 2020 at 2:31
Aravinda Meewalaarachchi
2,6691 gold badge31 silver badges27 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
{
"_id": {
"$oid": "5eb5f0a9d985888edb0523b0"
},
"subs": [{
"name": "list1",
"count": 0
}, {
"name": "list2",
"count": 0
}, {
"name": "list3",
"count": 0
}, {
"name": "list4",
"count": 0
}]
}
The answer is not based on mongojs but the syntax below should assist you.
db.collection.updateOne(({"subs.name":"list2"},{$inc:{"subs.$.count":1}})
Make sure that your count is int32 not a string. "Count": 0 not "Count":"0"
Aravinda Meewalaarachchi
2,6691 gold badge31 silver badges27 bronze badges
Comments
lang-js