Search code examples
mongodbmeteor

check if value exists in array field in mongodb


I want to check if user id exists inside an array field of mongodb (using meteor)

db.posts.find().pretty()

 {
        "_id" : "hT3ezqEyTaiihoh6Z",
        "body" : "hey\n",
        "authorId" : "AyJo5nf2Lkdqd6aRh",
        "createdAt" : ISODate("2016-05-13T06:19:34.726Z"),
        "updatedAt" : ISODate("2016-05-13T06:19:34.726Z"),
        "likecount" : 0,
        "already_voted" : [ ] }

 db.posts.find( { _id:"hT3ezqEyTaiihoh6Z"},{ already_voted: { $in : ["AyJo5nf2Lkdqd6aRh"]} }).count()

 1

It gives count value 1 , where as I am expecting it to be 0 .


Solution

  • Your logic is fine. Just the syntax is wrong.

    db.posts
      .find({
        _id: "hT3ezqEyTaiihoh6Z",
        already_voted: { $in: ["AyJo5nf2Lkdqd6aRh"] },
      })
      .count();
    

    This should work.