0

I am trying to make a request in a document with mongodb.

In this document

{
    "_id" : ObjectId("5bd19a92da24674fdabd26b6"),
    "search" : "try",
    "name" : "try",
    "email" : "yes@gmail.com",
    "password" : "$2a$10$YIRuApqDy/L8HU7R1k2SB.aC2hqH8xFDbl3/muF7PsoN6/SGzsH4q",
    "color" : 0,
    "profil" : "",
    "banner" : "",
    "desc" : "",
    "date" : 45587899,
    "friend" : [
            {
                    "id" : ObjectId("5bcee588ae409f434d35c76c")
            }
    ],
    "groupes" : [ ]
}

I'm looking to get just the id in friend, not all of the document just 1 id in friend with where i try this :

db.users.find({$and:[{"friend.id":"ObjectId(5bcee588ae409f434d35c76c)"},{"search":"try"}]})

It's not working i got no result.

Thank you for helping me.

MakeProps
  • 143
  • 4
  • 14
  • Possible dupe of https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection – JohnnyHK Oct 25 '18 at 14:09

2 Answers2

1

I am not 100% sure I do understand your question properly. You should be able to query the described document via the following query:

find(
  /* query by 'search' and the specific friend-id */
  {'friend.id': ObjectId("5bcee588ae409f434d35c76c"), search: 'try'}, 

  /* return only that 'friend' element which matches the queried 'friend-id' */
  {_id:0, friend:{$elemMatch:{id:ObjectId("5bcee588ae409f434d35c76c")}}}
)

You get the following result:

{
    "friend" : [ 
        {
            "id" : ObjectId("5bcee588ae409f434d35c76c")
        }
    ]
}
kongo2002
  • 1,006
  • 5
  • 11
-1
db.users.find({
    friend: {
        $elemMatch: {
            id: ObjectId("5bcee588ae409f434d35c76c")
        }
    },
    search: 'try'
})
Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26