MongoDB C# 驱动程序:如何对嵌套的嵌入式文档使用 $in 运算符?

MongoDB C# driver: how to use $in operator for nested embedded documents?

我正在尝试通过 MongoDB C# 驱动程序来使用 $in 运算符。

这是一个示例文档:

ObjectField:
    {
      "_id" : ObjectId("59421cd7f39cc1227cb7be55"),
      "ObjectName" : "Customer",
      "FieldName" : "Kind Customer",
      "KeyValues" : [{
          "Key" : "k11",
          "Value" : "v11"
        }, {
          "Key" : "k21",
          "Value" : "v21"
        }]
    }

这是我尝试的第一种方法:

var database = MongoDbClient.GetDatabase("Database");
var builder = Builders<ObjectField>.Filter;
var keys = new List<string>() { "k11", "k21" };
var filter = builder.Eq("ObjectName", "Customer") & builder.Eq("FieldName", "Kind Customer") & builder.In("KeyValues.Key", keys);
var projection = Builders<ObjectField>.Projection.Include("KeyValues.$");
var bsonDocuments = database.GetCollection<ObjectField>("ObjectField").Find(filter).Project(projection).ToList();

然而,它 returns 仅排在榜首 KeyValue

{
        "_id": ObjectId("59421cd7f39cc1227cb7be55"),
        "KeyValues": [{
            "Key": "k11",
            "Value": "v11"
        }]
    }

这是我尝试的第二种方法:

 var keys = new List<string>() { "k11", "k20" };
 var result = (from x in database.GetCollection<ObjectField>("ObjectField").AsQueryable()
                              where x.KeyValues.Any(y => keys.Contains(y.Key))
                              && x.ObjectName == "Customer" && x.FieldName == "Kind Customer"
                              select x).ToList();

在这种情况下,它返回了所有不包含在键中的嵌套记录。

var filter = Builders<XXXX>.Filter.In("_id", xxxx.Select(i => i.Id));
mongoClient.GetCollection<XXXX>("XXXX").DeleteMany(filter);