onurhb
onurhb

Reputation: 1181

C# MongoDB match any of elements in an array

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?

Upvotes: 2

Views: 13404

Answers (2)

wrzr123
wrzr123

Reputation: 31

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"});

Upvotes: 1

Saleem
Saleem

Reputation: 8978

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

Upvotes: 9

Related Questions