Mongoose: Filter collection based on values in another collection

谁说胖子不能爱 提交于 2019-12-23 02:54:40

问题


Consider documents that contain an arrays of ID of another collection, how can I find documents applying a filter based on the related collection using mongoose? I can't find my error

  Installation.aggregate(                        
                    [
                          // Stage 1
                          {
                                $lookup: {
                                      from: "users",
                                      localField: "_id",
                                      foreignField: "_id",
                                      as: "Users"
                                }
                          },

                          // Stage 2
                          {
                                $unwind: {
                                      path: "$Users"
                                }
                          },
                          // Stage 3
                          {
                                $match: 
                                      {"Users.Email1" : "test@test.com"}

                          }, 
                          {
                                $sort: { _id: -1 }
                          },
                          {
                                $limit: 10
                          }                            
                    ]
              ,function (err, installations) {

                   console.log(installations); //<<<<< Empty
                    /*
                    Installation.populate( 'Parent', '_id Email1','Company'), function(err,results) {
                          Installation.count(filter).exec(function (err, count) {
                                res.send({ success: true, results: installations, total: count });
                          });
                    };
                    */                                                             
              });

Thanks in advance Andrea


回答1:


You can do this using aggregate query:

db.collectionA.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $lookup: {
                from: "collectionB",
                localField: "_id",
                foreignField: "_id",
                as: "collectionBData"
            }
        },

        // Stage 2
        {
            $unwind: {
                path : "$collectionBData"
            }
        },

        // Stage 3
        {
            $match: {
                "collectionBData.email": "your@email.address"
            }
        },

    ]

);

Hope this solves your query.

Also, in Mongo, we use naming conventions as collections instead of table and _id instead of id.



来源:https://stackoverflow.com/questions/51148744/mongoose-filter-collection-based-on-values-in-another-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!