2

How do you check if a particular string value exists in a field in a mongo collection?

The standard collection.find returns a cursor however, I am trying to get a true or false response.

So I am doing the following which is incorrect.

var booleanResponse = collection.find({}, {'field': 'valueToCheck'})
console.log(booleanResponse)

I also tried the following but the operation checks agains an array but my field holds a string...

var booleanResponse = collection.find({},
    { field: { $exists: true, $nin: [valueToCheck]} })
the
  • 21,007
  • 11
  • 68
  • 101
meteorBuzz
  • 3,110
  • 5
  • 33
  • 60

2 Answers2

2

You can just check the count like this:

var fancyPostsExist = Posts.find({type: 'fancy'}, {limit: 1}).count() > 0;

In this example, fancyPostsExist will be a true if there exist Posts with a field type equal to 'fancy', and false otherwise.

David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • Using `findOne` will be more effective? "Stop searching when you've found one" sounds faster than "Find all and then count them". – Peppe L-G Mar 09 '15 at 17:53
  • Yeah that's true. I added a limit to the answer to solve this. In theory that should be better than a `findOne` because it doesn't return the document. Either way, `type` would need to be indexed if speed was really an issue. – David Weldon Mar 09 '15 at 17:57
1

If you want to check if there is any record in a specific collection whose field field has the value value you can do:

var hasValue = YourCollection.findOne({field: 'value'}) === undefined ? false : true
Rafael Quintanilha
  • 1,413
  • 11
  • 10
  • [Do not use the `===` operator to check for undefined!](http://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized-which-method-is-b) – Kyll Mar 09 '15 at 16:32
  • Rafael's code returns the true or false value if the value exists in field. @Kyll - please explain why not to use the === operator to check for undefined? – meteorBuzz Mar 09 '15 at 16:47
  • The link I have provided in my comment already contains a lot of great answers, from people who understand it better than me. But for example, if a variable has the value `undefined` (but IS defined!), then the condition won't return the good solution. More in the link =) – Kyll Mar 09 '15 at 17:01
  • @Kyll there is indeed situations where ``typeof`` is the silver bullet, when the variable is not declared, for example. Nonetheless, in the context of the question, my answer will never fall into some of this pitfalls. But for sure you can be pragmatic and go with the ``typeof`` way. – Rafael Quintanilha Mar 09 '15 at 18:29
  • David I see your point. Importantly - that find() only returns the cursor whereas findOne() returns the whole document which I dont need – meteorBuzz Mar 10 '15 at 00:13