【问题标题】:Merge parent field and its nested array field in mongodb在mongodb中合并父字段及其嵌套数组字段
【发布时间】:2020-12-22 19:08:57
【问题描述】:

我有一个像下面这样的集合

{
    "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
        }
    ]
}

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

{
    "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"
    }
  }
])

【问题讨论】:

    标签: c# mongodb aggregation-framework mongodb-.net-driver


    【解决方案1】:

    我已经像下面这样管理它,如果将来有人需要它,我想分享一下。

    经过一番阅读,我个人决定走一对多的道路,分开投票。

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      相关资源
      最近更新 更多