使用多个ID(内部数组)在Mongodb中过滤查询

时间:2018-08-23 07:19:20

标签: asp.net-mvc mongodb mongodb-query mongodb-.net-driver mongodb-csharp-2.0

CommentCollection
{
 "_id":"5b63f0f23846b70011330889",
  "CommentType":"task",
  "EntityReferenceId":"6082ef25-6f9a-4874-a832-f72e0f693409",
  "Threads":[
  {
     "_id":"69bcef71-3695-4340-bdec-4a6e4c58c490",
     "CommentType":"task",
     "UserId":ObjectId("52ffc4a5d85242602e000000"),         
     "CommentByUserType":"Admin",
     "EntityReferenceId":"6082ef25-6f9a-4874-a832-f72e0f693409",
     "Content":"fdffd",

  },
  {
     "_id":"69bcef71-3695-4340-bdec-4a6e4c58c490",
     "CommentType":"task",
     "UserId":ObjectId("52ffc4a5d85242602e000000"),         
     "CommentByUserType":"Admin",
     "EntityReferenceId":"6082ef25-6f9a-4874-a832-f72e0f693409",
     "Content":"fdffd",

  }
 ]
}

在这里,我必须根据两个条件,从asp.net核心编写一个Mongodb过滤器查询, 首先,我想通过 EntityReferenceId 获取CommentCollection,然后想从第一个结果中通过 id 查找特定线程。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我得到了答案,我已经编写了如下的方法

 public async Task<bool> UpdateCommentAsync(Threads thread)
    {
        var builder = Builders<Comments>.Filter;
        var filter = builder.Empty;
        var update = Builders<Comments>.Update.Set("Threads.$[i].Content", thread.Content);
        var arrayFilters = new List<ArrayFilterDefinition> { new JsonArrayFilterDefinition<Threads>("{'i._id': '" + thread.Id + "'}") };
        var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };
        var result = await _context.Comments.UpdateManyAsync(filter, update, updateOptions);
        return result.ModifiedCount > 0;
    }