使用MongoDB C#驱动程序在嵌套数组上使用过滤器构建器进行查询

时间:2015-06-22 17:05:40

标签: c# mongodb mongodb-query mongodb-.net-driver mongodb-csharp-2.0

考虑将以下对象结构存储为文档:

var app = angular.module('scattChartApp', ['nvd3'])
.controller('MainCtrl', function($scope, $http) {

  $http.get('chartdata.json').success(function(response) {
      response.options.chart.tooltipContent = function(key) {
         return '<h3>' + key + '</h3>';
      };
      $scope.options = response.options;
      $scope.data = response.data;
  });


});

对驱动程序使用LINQ样式查询我可以public class Foo { public string Id { get; set; } public ICollection<FooBar> Bars { get; set; } // ... } public class FooBar { public string BarId { get; set; } // ... } 包含Find Foo的所有FooBar,如下所示:

BarId

如何使用FilterDefinitionBuilder代替var foos = await m_fooCollection.Find( f => f.Bars.Any( fb => fb.BarId == "123") ).ToListAsync(); 上的内联LINQ来实现相同的查询?

1 个答案:

答案 0 :(得分:12)

您需要执行的查询使用$elemMatch查询运算符。

所以,这个查询使用lambda表达式

var findFluent = collection.Find(f => f.Bars.Any(fb => fb.BarId == "123"));

使用FilterDefinitionBuilder

等效于此查询
var findFluent = collection.Find(Builders<Foo>.Filter.ElemMatch(
    foo => foo.Bars, 
    foobar => foobar.BarId == "123"));