chintan zaveri
chintan zaveri

Reputation: 93

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 .

Upvotes: 7

Views: 35429

Answers (2)

Divyeshkumar Pujari
Divyeshkumar Pujari

Reputation: 51

You can just simply use count method. Don't need to use two operation like Find and then count.

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

Upvotes: 5

Sudheer Jami
Sudheer Jami

Reputation: 737

Your logic is fine. Just the syntax is wrong.

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

This should work.

Upvotes: 22

Related Questions