我正在尝试使用$in
使用 MongoDB C# 驱动程序的运算符。
这是一个示例文档:
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();
但是,它只返回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();
在这种情况下,它返回所有未包含在键中的嵌套记录。