3

I have document

 {
    "_id" : ObjectId("5aebf141a805cd28433c414c"),
    "forumId" : ObjectId("5ae9f82989f7834df037cc90"),
    "userName" : "Name",
    "usersLike" : [ 
        "1","2"
    ],
    "comment" : "Comment",
}

I want to remove value from usersLike array if the value exists, or add if the value does not exist.

Eg:

If I try to push 1 into usersLike, it should return

{
    "_id" : ObjectId("5aebf141a805cd28433c414c"),
    "forumId" : ObjectId("5ae9f82989f7834df037cc90"),
    "userName" : "Name",
    "usersLike" : [ 
        "2"
    ],
    "comment" : "Comment",
}

How can I query it..??

7
  • Value exists as in? The array usersLike exists or a particular value should exist in usersLike? Commented May 4, 2018 at 7:04
  • Can you please give a more concrete example? Commented May 4, 2018 at 7:08
  • If the value 1 exists in the array usersLike it should be removed. Otherwise, the value 1 should be added to the array usersLike. Commented May 4, 2018 at 7:45
  • I think more to the point here is why would you not know it exists? If you are trying to build something like "this site" or "likes" on facebook for example, then the data in the page actually knows the current user already has a vote. So if I "upvote" this question, and then come back to this page later, part of the page data includes the record of "my vote", so before I even send a request to vote again I can already tell I have voted, hence no need to send the request. Commented May 4, 2018 at 7:51
  • I think you're trying to "blind toggle" such values under just those circumstances, but it's not really the correct approach. As stated, your "client" should already know if a user has voted/liked. For a bit more detail, see How to Model a “likes” voting system with MongoDB. Commented May 4, 2018 at 7:52

4 Answers 4

6

MongoDB version 4.2+ introduces pipelined update. Which means we can now use aggregation operators while updating. this gives us a lot of power.

db.collection.updateOne(
    {
        _id: ObjectId("597afd8200758504d314b534")
    },
    [
        {
            $set: {
                usersLike: {
                    $cond: [
                        {
                            $in: ["1", "$usersLike"]
                        },
                        {
                            $setDifference: ["$usersLike", ["1"]]
                        },
                        {
                            $concatArrays: ["$usersLike", ["1"]]
                        }
                    ]
                }
            }
        }
    ]
)
Sign up to request clarification or add additional context in comments.

Comments

0

Mongodb doesn't support conditional push or pull update. However you can still do it by using find:

 db.collectionName.find({_id:ObjectId("597afd8200758504d314b534"),usersLike:{$in:["1"]}}).pretty()

if id exist in usersLike than pull else push.

Or you use the update query to pull as:

db.collectionName.update({
    _id: ObjectId("597afd8200758504d314b534"),
    usersLike: {
        $in: ["1"]
    }
    }, {
        $pull: { 'usersLike': "1" }
    }, { multi: true })

And to push you can use:

db.collectionName.update({
   _id:ObjectId("597afd8200758504d314b534"), 
   usersLike:{$nin:["1"]
}},{
   $push:{'usersLike':"1"}
}, {multi: true})

Comments

0

Try this :

db.collectionName.update({_id:ObjectId("597afd8200758504d314b534")},{$pull:{'usersLike':"1"}}, {multi: true})

3 Comments

Can't be done using this query... This query will only extract($pull) the id, can't add($push) and as the question says $push and $pull should be done simultaneously...
Mongodb doesn't support conditional push or pull update. However you can still do it by using find (db.collectionName.find({_id:ObjectId("597afd8200758504d314b534"),usersLike:{$in:["1"]}}).pretty()) , if id exist in usersLike than pull else push.
yes it can be done... but he wants it in a single query, which is not possible
0

Try this

if db.collectionName.find({'_id':ObjectId("5aebf141a805cd28433c414c"),'usersLike:{'$in:['1']}}).count() > 0:

    db.collectionName.update({'_id':ObjectId("5aebf141a805cd28433c414c")},{'$pull':{'usersLike':'1'}})

else:
    db.collectionName.update({'_id':ObjectId("5aebf141a805cd28433c414c")},{'$addToSet':{'usersLike':'1'}})

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.