1

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!

3
  • I think is using array filters: docs.mongodb.com/manual/reference/command/update/… - stackoverflow.com/questions/51605347/… Commented May 9, 2020 at 0:24
  • 1
    is you try to update the values only using mongojs provided functions or just need to update those values by using javascript functions? Commented 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 ? Commented May 9, 2020 at 1:43

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0
{
"_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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.