7

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 .

2 Answers 2

24

Your logic is fine. Just the syntax is wrong.

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

This should work.

Sign up to request clarification or add additional context in comments.

Comments

5

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"] }
  });

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.