Home > Enterprise >  MongoDB Select documents by the value of a specific field
MongoDB Select documents by the value of a specific field

Time:12-01

MongoDB - userModel (simplified)

  {
    _id: "exampleid1",
    name: "examplename1",
    following: [
      {
        _id: "exampleid2",
        name: "examplename2"
      },
      {
        _id: "exampleid3",
        name: "examplename3"
      }
    ],
    followers: [
      {
        _id: "exampleid4",
        name: "examplename4"
      },
      {
        _id: "exampleid5",
        name: "examplename5"
      }
    ]
  }

Hey, I'm building a social media platform and I need to get from the database only the users that I follow.

I tried the query below, but gives me nothing:

User.find( { "followers": { _id: "exampleid1"} } )

CodePudding user response:

Try to divide the document selection ({_id: "exampleid1"}) from the projection ({followers: 1, _id: 0}):

db.collection.find({
  _id: "exampleid1"
},
{
  followers: 1,
  _id: 0
})

See how it works on the playground example

  • Related