0

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

In this document

{
    "_id" : ObjectId("5bd19a92da24674fdabd26b6"),
    "search" : "try",
    "name" : "try",
    "email" : "[email protected]",
    "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.

1

2 Answers 2

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")
        }
    ]
}
0
-1
db.users.find({
    friend: {
        $elemMatch: {
            id: ObjectId("5bcee588ae409f434d35c76c")
        }
    },
    search: 'try'
})
1
  • 2
    Can you explain why this is the answer to the question ? Oct 25, 2018 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.