2

I have shops collection and user collection with list of shops ids inside of it as strings.

example of shop document:

    {
            "_id" : ObjectId("5a0c6797fd3eb67969316ce2"),
            "picture" : "http://placehold.it/150x150",
            "name" : "Genmom",
            "email" : "[email protected]",
            "city" : "Rabat",
            "location" : {
                    "type" : "Point",
                    "coordinates" : [
                            -6.79387,
                            33.83957
                    ]
            }
    }

example of user collection:

{
            "_id" : ObjectId("5c04b943ff491824b806686a"),
            "email" : "[email protected]",
            "password" : "$2a$10$4Wt5Rn6udxREdXCIt3hGb.sKhKUKOlyiYKmLTjYG3SqEPKFSw9phq",
            "likedShops" : [
                    "5a0c6797fd3eb67969316ce2",
                    "5c07ada8ff49183284e509d1",
                    "5c07acc1ff49183284e509d0"
            ],
            "dislikedShops" : [ ]
}

I want to return the detail of the likedShops.

4
  • What is the type of likedShops ids? String or OBjectID? And what version of mongo you are using? Commented Dec 5, 2018 at 16:38
  • @AnthonyWinzlet String Commented Dec 5, 2018 at 16:39
  • And the mongodb version? Commented Dec 5, 2018 at 16:41
  • mongodb version 4.2 Commented Dec 5, 2018 at 16:42

1 Answer 1

5

You can use below $lookup aggregation

db.users.aggregate([
  { "$lookup": {
    "from": "shops",
    "let": { "likedShops": "$likedShops" },
    "pipeline": [
      { "$match": { "$expr": { "$in": ["$_id", "$$likedShops"] }}}
    ],
    "as": "likedShops"
  }}
])

Or if your ids are string then use $toString aggregation with the ObjectIds

db.users.aggregate([
  { "$lookup": {
    "from": "shops",
    "let": { "likedShops": "$likedShops" },
    "pipeline": [
      { "$match": { "$expr": { "$in": [{ "$toString": "$_id" }, "$$likedShops"] }}}
    ],
    "as": "likedShops"
  }}
])
Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting "errmsg" : "$in requires an array as a second argument, found: missing"
by the way i have some users without likedShops field:)
Your some of the documents doesn't contain the likedShop field. See this

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.