合并 parent 字段及其在 mongodb 中的嵌套数组字段

Merge parent field and its nested array field in mongodb

我有一个 collection 如下所示

{
    "id":"5fd13c33ac0277c435117519",
    "content":"test",
    "votes":[
        {
            "user":"22",
            "isLike":true
        },
        {
            "user":"25",
            "isLike":false
        },
        {
            "user":"43",
            "isLike":false
        }
    ]
},
{
    "id":"5fd13c33ac0277c435237443",
    "content":"test 2",
    "votes":[
        {
            "user":"25",
            "isLike":true
        },
        {
            "user":"43",
            "isLike":false
        }
    ]
}

如何通过查询 votes.user -ie 来使用 c# 驱动程序获得以下结果。 25- 然后合并来自 parent 和嵌套数组的这 2 个字段?

{
    "id":"5fd13c33ac0277c435117519",
    "isLike":false
},
{
    "id":"5fd13c33ac0277c435237443",
    "isLike":true
}

编辑:经过一些尝试后我得到了结果,但在 mongoplayground.net 上失败了,但仍然不确定如何通过 C# 驱动程序转换它。

db.collection.aggregate([
  {
    $unwind: "$votes"
  },
  {
    $match: {
      "votes.user": "25"
    }
  },
  {
    $replaceWith: {
      id: "$id",
      isLike: "$votes.isLike"
    }
  }
])

我是这样管理的,如果以后有人需要的话想分享一下。

经过一些阅读,我个人决定走一对多的道路,分开收集选票。

var match = new BsonDocument("votes.user", 25);

var replace = new BsonDocument(new List<BsonElement> {
    new BsonElement("id", "$id"),
    new BsonElement("isLike", "$votes.isLike"),
});

return await _collection.Aggregate()
    .Unwind(c => c.votes)
    .Match(match)
    .ReplaceWith<UserVote>(replace)
    .ToListAsync();