How to make nested queries in MongoDb that works like nested Sql select queries

前端 未结 6 1057
不知归路
不知归路 2021-02-05 11:02

I want to make an efficient query in MongoDb to find all users who have their userids listed in a usergroup. Ideally I want to make this as a single request to Mongodb. What I w

6条回答
  •  孤街浪徒
    2021-02-05 11:55

    db.usergroup.aggregate([
      { $match: { _id: "g1" } }, 
      { $unwind: "$Users" }, 
      { $lookup: 
        { from: "user", localField: "Users", foreignField: "_id", as: "user" } 
      } 
    ])
    
    // result :
    { "_id" : "g1", "Users" : "u2", "user" : [ { "_id" : "u2", "Name" : "u1 name" } ] }
    { "_id" : "g1", "Users" : "u3", "user" : [ { "_id" : "u3", "Name" : "u3 name" } ] }
    
    

提交回复
热议问题