How to join query in mongodb?

后端 未结 10 2203
情深已故
情深已故 2020-11-29 03:22

I have user document collection like this:

User {
   id:\"001\"
   name:\"John\",
   age:30,
   friends:[\"userId1\",\"userId2\",\"userId3\"....]
}
         


        
10条回答
  •  抹茶落季
    2020-11-29 04:11

    You can do it in one go using mongo-join-query. Here is how it would look like:

    const joinQuery = require("mongo-join-query");
    
    joinQuery(
        mongoose.models.User,
        {
            find: {},
            populate: ["friends"],
            sort: { age: 1 },
        },
        (err, res) => (err ? console.log("Error:", err) : console.log("Success:", res.results))
    );
    

    The result will have your users ordered by age and all of the friends objects embedded.

    How does it work?

    Behind the scenes mongo-join-query will use your Mongoose schema to determine which models to join and will create an aggregation pipeline that will perform the join and the query.

提交回复
热议问题