如何使用mongoose搜索在不同字段中查找重复值?

这是示例文档:

{
 "followers": {
               {
                "_id": "5bf6d610d3a3f31a6c75a9f4"
               },
               {
                "_id": "5bf6d610d3a3f31a6c75a8c3"
               }
              },
 "following": {
               {
                "_id": "5bf6d610d3a3f31a6c75a9f4"
               },
               {
                "_id": "5bf6d610d3a3f31a6c75b7a2"
               }
              },
}

我想在_idfollowers字段下找到相同的following值。

预期输出:
{
 {
  "_id": "5bf6d610d3a3f31a6c75a9f4"
 }
}

我应该使用什么查询?

最佳答案

尝试以下操作:

db.collection.aggregate([
    { $unwind : "$followers"},
    { $unwind : "$following"},
    { $project : {
        _id: 0,
        matchId: { $cond: [ {$eq: [ "$followers._id", "$following._id" ]} ,
          "$following._id", null ] }
    }},
    {$match : {"matchId" : {$ne : null}}}
])

输出:
/* 1 */
{
    "matchId" : "5bf6d610d3a3f31a6c75a9f4"
}

08-19 14:22