我正在尝试使用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();
但是,它只从列表中返回前一个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();
在这种情况下,它返回了所有未包含在键中的嵌套记录。
答案 0 :(得分:0)
var filter = Builders<XXXX>.Filter.In("_id", xxxx.Select(i => i.Id));
mongoClient.GetCollection<XXXX>("XXXX").DeleteMany(filter);