check if value exists in array field in mongodb
Asked Answered
B

2

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 .

Blink answered 13/5, 2016 at 6:22 Comment(0)
P
22

Your logic is fine. Just the syntax is wrong.

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

This should work.

Polymyxin answered 13/5, 2016 at 6:39 Comment(0)
K
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"] }
  });
Karalee answered 1/10, 2021 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.