2

I have documents like this:

/* 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"
}

And a list of sources like this:

list = ['VG', 'IGN']

I want to return only the documents with source equals 'IGN' or 'VG' (any of elements in list)

How can I do this with the official C# mongodb driver?

2 Answers 2

9

Assuming you are using MongoDB C# driver version 2.2, you can use FilterDefinitionBuilder class to filter out desired results.

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();

docs will hold only those documents with source either VG or IGN. Based on your sample data, it will have 4 documents.

I'll recommend you to have a look at how to Find or Query Data with C# Driver

Sign up to request clarification or add additional context in comments.

2 Comments

Getting error: The serializer for field 'Source' must implement IBsonArraySerializer and provide item serialization info.
Make sure you are including proper assembly references.
1

It's a bit late, but I had the same question as OP and actually the accepted answer is wrong. AnyIn is the correct filter if your database object itself contains an array where you want to search. In OP's (and also in my) case, the simple In filter is the correct one to use:

var filter = Builders<BsonDocument>.Filter.In("Source", new[]{"VG", "IGN"});

or with lambda

var filter = Builders<BsonDocument>.Filter.In(o => o.Source, new[]{"VG", "IGN"});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.