简体   繁体   中英

Monk / Mongodb performing find inside callback of another find

I have the following document structure to record a user's friends list:

{ 
    "_id" : ObjectId("5df4d0ac6480078812e7b2ff"), 
    "name" : "Alice"
    "friends" : [ "Bob", "John" ] 
}

When receiving a request for a user, say "Alice" , I'd like to retrieve Alice's friends as well as their _id field, returning a response of an array of friends' names and their _id , eg

[{"name": "Bob", "_id": "abcdef"}, {"name": "John", "_id": "ghjikl"}

How do I go about doing this in Monk?

My idea was to use collection.find() on the user to retrieve the friends list, then loop through it to perform another find() to get their _id . But that doesn't work as I can't update variables from outside the nested find() callback function.

This aggregation will gives you something close to what you want:

db.users.aggregate([
  {
    "$match": {
      "name": "Alice"
    }
  },
  {
    "$lookup": {
      "from": "users",
      "as": "friends",
      "localField": "friends",
      "foreignField": "name"
    }
  },
  {
    "$project": {
      "_id": 0,
      "friends._id": 1,
      "friends.name": 1,

    }
  }
])

Output:

[
  {
    "friends": [
      {
        "_id": "abcdef",
        "name": "Bob"
      },
      {
        "_id": "ghjikl",
        "name": "John"
      }
    ]
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM