Home > Software design >  MongoDb find function to select only specific post
MongoDb find function to select only specific post

Time:10-26

this is the first time im using stack overflow cause i have a problem and i cant find a solucion im just starting out in data bases and im getting this problem. enter image description here

The documentation says it should work but when i try to get the posts only with the name post1 y returns both posts. I might be being stupid but can someone explain why this isnt doing what it should??

Want to only get post1 and not post2 using posts.name: post1, but gave me both posts

CodePudding user response:

This is how Mongo works, the "query" field matches the document, the array field is part of that document so it is returned in full.

What you want to do is use the $ projection operator in your query:

The positional $ operator limits the contents of an to return the first element that matches the query condition on the array.

Like so:

db.collection.find({
  "posts.name": "post1"
},
{
  "posts.name.$": 1
})

Mongo Playground

  • Related