1

I am trying to find document based on profileID in MongoDB. I want to check if string postid exists in array or not. How I can do that? I tried $all.

Mongo data:

{
  "profileId": "abc",
  "likedPosts": [
    'post1',
    'post2'
  ]
}

Trying to find if post1 exists in array:

findOne({
  profileId
}, {
  likedPosts: {
    $all: ['post1']
  }
}, )
1

1 Answer 1

2

If you want to check if a string exists in an array field you can simply do:

findOne({
  profileId,
  likedPosts: 'post1'
  }
}, )

Docs

Also you might notice i have made the whole query as the first parameter. The second parameter is usually the callback to run, once the query has executed.

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

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.