Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How I can find if string exists inside mongodb Array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading