0

我有一个用户集合,其中每个元素都有一个联系人列表,我想创建一个聚合,给定用户的 id,对每个联系人进行 $ 查找并从同一集合返回用户的信息用户

用户集合看起来像

[
    {
        '_id': 1,
        'username': 'user 1',
        'contacts_list': [
            {
                'contact_id': '2'
            },
            {
                'contact_id: 3
             }
        ]
    }, 
    {
        '_id': 2,
        'username': 'user 2',
        'contacts_list': [
            {
                'contact_id': 1
            }
        ]
    },
    {
        '_id': 3,
        'username': 'user 3',
        'contacts_list': [
            {
                'contact_id': 1
            }
        ]
    }
]

我试过这样的东西

[
  {
    '$match': {
      '_id': 1
    }
  }, {
    '$unwind': {
      'path': '$contacts_list', 
      'preserveNullAndEmptyArrays': true
    }
  }, {
    '$lookup': {
      'from': 'users', 
      'localField': 'contacts_list.contact_id', 
      'foreignField': '_id', 
      'as': 'contact'
    }
  }, {
    '$group': {
      '_id': '$_id',
      '$push': {
        'username': 'contact.username'
       }
]

但我只从其中一位用户那里得到了信息,谢谢你的帮助

4

0 回答 0