如何在Mongo中的一个管道中加入和排序几个集合

时间:2016-11-29 10:52:31

标签: mongodb sorting meteor

我想列出一个按照他们背后的关系排序的用户列表。

为此,我需要比较3个集合的ID以按顺序排序 -

  

首先:'收到来自',

的请求      

第二:'发送请求',

     

第三名:'朋友',

     第四:'其他人'

更新:输入

识别用户背后关系的集合

db.friends.find({userId: currentUser});
    // {"_id" : "qwC7LrtaZtQsShtzT", "userId" : "rbrwhh2AQY8mzmzd3", "friendId" : "4y7pG7p2gcGgm5ayj",} 
db.requests.find({userId: currentUser});
   // {"_id" : "PgC7LrtaZtQsShtzT", "userId" : "tHuxnWxFLHvcpRgHb", "requesterId" : "jZagPF7bd4aW8agXb",}

包含所有用户及其信息的主要收藏

db.users.find({userId: currentUser});
      // {"_id" : "4y7pG7p2gcGgm5ayj", profile: {name: 'Andrey', second: 'Andrey'}} -> Same person(id) like in 'friends' collection.
     // {"_id": "tHuxnWxFLHvcpRgHb", profile: {name: 'Erick', second: 'Erick'} -> same person who have receive request. 

现在我需要聚合'用户'集合,定义与前两个集合(朋友,请求)匹配的分数。

我试图这样做

db.users.aggregate([
    // here i tried to compare _id and requesterId to fetch all who received request from me:
    {$lookup: {from: 'requests', localField: "_id", foreignField: "requesterId", as: "sentRequest"}},
    {$unwind: '$sentRequest'},
    {$project: {_id: '$sentRequest.userId', profile: 1, count: {$add: [2]}}},
    // And here I tried to get all friends
    {$lookup: {from: 'requests', localField: "_id", foreignField: "friendId", as: "friends"}},
    {$unwind: '$friends'},
    {$project: {_id: '$friends.userId', profile: '$profile', count: {$add: [3]}}}

]);

但结果我只得到最后一部分(朋友)和另一个问题

[ { _id: 'rbrwhh2AQY8mzmzd3', //this field is responds to person which I looking for
 profile: //But profile data is given from .users and its not respont to person with given id
  { firstName: 'Andrey', 
    lastName: 'Andrey',
   userImg: '/img/user.jpg',
   userDescription: null },
  count: 3 } ]

更新

预期结果

//Given: 3 collections
db.users -> provide all additional info about all users
db.requests -> groups IDs of two users 'requester' and 'receiver'
db.friends -> groups IDs of two users 'friend' and 'user', document has pair where value are swapped (but it's not important in this task);

//Need to combine all of this three collections in one queue, to sort users by their relationships between them, in kind of this list:
// 1 - Requests; 2 - Friends; 3 - Other users


// Expected result:
[   
    // I've got request From:
    { "_id": "tHuxnWxFLHvcpRgHb", // _id must be equal to user who sent request and _id from db.users
        "profile": // this value used from db.users
        {   
            "firstName": "Ana", 
            "lastName": "de Armas",
            "userImg": "/img/user.jpg",
            "userDescription": null 
        },
            "weight": 4 // given value to make sorting then
    },
    // I sent request To: 
    { "_id": "4y7pG7p2gcGgm5ayj", 
        "profile": 
        {   
            "firstName": "John", 
            "lastName": "Bonjovi",
            "userImg": "/img/user.jpg",
            "userDescription": null 
        },
            "weight": 3 
    },
    // My friend:
    { "_id": "jZagPF7bd4aW8agXb", 
        "profile": 
        {   
            "firstName": "Jessica", 
            "lastName": "Alba",
            "userImg": "/img/user.jpg",
            "userDescription": null 
        },
            "weight": 2 
    },
    // Unknown user:
    { "_id": "DdX8sPuAoZqKpa6nH", 
        "profile": 
        {   
            "firstName": "Sheldon", 
            "lastName": "Cooper",
            "userImg": "/img/user.jpg",
            "userDescription": null 
        },
            "weight": 1 
    }
]

我尝试使用$ lookup进行聚合 - 但它不适用于3个集合。

结果我需要返回队列,在那里可以在新的联合集合中设置新字段 - 权重。有可能按此字段排序。

1 个答案:

答案 0 :(得分:0)

最新的Mongo 3.4版本,您将使用 $facet 来处理跨多个聚合管道的相同数据,并将所有聚合的结果连接到单个输出

db.users.aggregate([
    { "$match": { "_id":1} },
    {
        "$facet": {
            "Received": [
                 {$lookup: {from: 'requests', localField: "_id", foreignField: "userId", as: "receivedRequest"}},
                 {$unwind: '$receivedRequest'},
                 {$lookup: {from: 'users', localField: "receivedRequest.requesterId", foreignField: "_id", as: "receivedUser"}},
                 {$project: {_id: '$receivedRequest.requesterId', profile: '$receivedUser.profile', weight: {$add: [4]}}}
            ],
            "Sent": [
                 {$lookup: {from: 'requests', localField: "_id", foreignField: "requesterId", as: "sentRequest"}},
                 {$unwind: '$sentRequest'},
                 {$lookup: {from: 'users', localField: "sentRequest.userId", foreignField: "_id", as: "sendUser"}},
                 {$project: {_id: '$sentRequest.userId', profile: '$sendUser.profile', weight: {$add: [3]}}}
            ],
            "Friends": [
                 {$lookup: {from: 'friends', localField: "_id", foreignField: "userId", as: "friends"}},
                 {$unwind: '$friends'},
                 {$lookup: {from: 'users', localField: "friends.friendId", foreignField: "_id", as: "friendUser"}},
                 {$project: {_id: '$friends.friendId', profile: '$friendUser.profile', weight: {$add: [2]}}}
            ],
            "Others": [
                {$lookup: {from: 'friends', localField: "_id", foreignField: "friendId", as: "others"}},
                 {$unwind: '$others'},
                 {$lookup: {from: 'users', localField: "others.userId", foreignField: "_id", as: "other"}},
                 {$project: {_id: '$others.userId', profile: '$other.profile', weight: {$add: [1]}}}
            ]
        }
    }
]).pretty()

示例输出:

{
        "Received" : [
                {
                        "_id" : 3,
                        "profile" : [
                                {
                                        "name" : "John"
                                }
                        ],
                        "weight" : 4
                }
        ],
        "Sent" : [
                {
                        "_id" : 4,
                        "profile" : [
                                {
                                        "name" : "Jessica"
                                }
                        ],
                        "weight" : 3
                }
        ],
        "Friends" : [
                {
                        "_id" : 2,
                        "profile" : [
                                {
                                        "name" : "Ana"
                                }
                        ],
                        "weight" : 2
                }
        ],
        "Others" : [
                {
                        "_id" : 5,
                        "profile" : [
                                {
                                        "name" : "Sheldon"
                                }
                        ],
                        "weight" : 1
                }
        ]
}