How to join query in mongodb?

后端 未结 10 2202
情深已故
情深已故 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:05
    var p = db.sample1.find().limit(2) , 
        h = [];
    for (var i = 0; i < p.length(); i++) 
    {
      h.push(p[i]['name']);
    }
    db.sample2.find( { 'doc_name': { $in : h } } ); 
    

    it works for me.

    0 讨论(0)
  • 2020-11-29 04:10

    one kind of join a query in mongoDB, is ask at one collection for id that match , put ids in a list (idlist) , and do find using on other (or same) collection with $in : idlist

    u = db.friends.find({"friends": ? }).toArray()
    idlist= []
    u.forEach(function(myDoc) { idlist.push(myDoc.id ); } )
    db.friends.find({"id": {$in : idlist} } )
    
    0 讨论(0)
  • 2020-11-29 04:10

    Only populate array friends.

    User.findOne({ _id: "userId"})
    .populate('friends')
    .exec((err, user) => {
        //do something
    });
    

    Result is same like this:

    {
        "_id" : "userId",
        "name" : "John",
        "age" : 30,
        "friends" : [
            { "_id" : "userId1", "name" : "Derek", "age" : 34 }
            { "_id" : "userId2", "name" : "Homer", "age" : 44 }
            { "_id" : "userId3", "name" : "Bobby", "age" : 12 }
        ]
    }
    

    Same this: Mongoose - using Populate on an array of ObjectId

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题