我有这样的文件:
/* 1 */
{
"_id" : ObjectId("573f3944a75c951d4d6aa65e"),
"Source" : "IGN",
"Country" : "US"
}
/* 2 */
{
"_id" : ObjectId("573f3d41a75c951d4d6aa65f"),
"Source" : "VG",
"Country" : "Norway"
}
/* 3 */
{
"_id" : ObjectId("573f4367a75c951d4d6aa660"),
"Source" : "NRK",
"Country" : "Norway"
}
/* 4 */
{
"_id" : ObjectId("573f4571a75c951d4d6aa661"),
"Source" : "VG",
"Country" : "Norway"
}
/* 5 */
{
"_id" : ObjectId("573f468da75c951d4d6aa662"),
"Source" : "IGN",
"Country" : "US"
}
Run Code Online (Sandbox Code Playgroud)
以及类似这样的资源列表:
list = ['VG', 'IGN']
Run Code Online (Sandbox Code Playgroud)
我只想返回源等于“ IGN”或“ VG”(列表中的任何元素)的文档
如何使用官方C#mongodb驱动程序执行此操作?
假设您使用的是MongoDB C#驱动程序2.2版,则可以使用FilterDefinitionBuilder类来过滤出所需的结果。
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
... Your class and method declaration ...
IMongoClient client = new MongoClient ("mongodb://localhost:27017/test");
IMongoDatabase database = client.GetDatabase("test");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument> ("collection");
var filter = Builders<BsonDocument>.Filter.AnyIn ("Source", new[]{"VG", "IGN"});
var cursor = await collection.FindAsync (filter);
var docs = cursor.ToList();
Run Code Online (Sandbox Code Playgroud)
docs只能容纳这些文件source要么VG或IGN.根据您的样本数据,这将有4号文件。
我建议您看看如何使用C#驱动程序查找或查询数据