finnTheHumin
finnTheHumin

Reputation: 165

C# MongoDB find in Array

I have this query in mongodb:

db.getCollection('emails').find({"to.address": {$in:['[email protected]']}})

I have to convert it into C# code. I've searched a lot already and nothing seems to fit my needs.

I even did an elem match:

MongoCursor<Email> csr = ConnectionHandler.Collection.Find(Query<Email>.ElemMatch(t => t.to(Query<Email.Address>).In(a => a.address, emails)));

This is what I've come up with in C# so far:

var emails = emailAddresses.Select(e => e.emailAddress);
MongoCursor<Email> csr = ConnectionHandler.Collection.Find(Query<Email>.EQ("to.address", (Query<Email.Address>.In()));

It's incomplete. and obviously not close to the right solution.

Hope someone can help!

Thanks!

Upvotes: 1

Views: 194

Answers (1)

finnTheHumin
finnTheHumin

Reputation: 165

Answering my own question.

The answer is as simple as this:

var emails = new BsonArray(emailAddresses.Select(e => e.emailAddress));
MongoCursor<Email> csr = ConnectionHandler.Collection.Find(Query.In("to.address", emails));

Apparently, you can do a query without using a type, so instead of using this:

Query<Email>.EQ

you can actually just slap your query in like this:

Query.In("to.address", emails)

just as long as the variable you are storing it into is typed with the object that you want, as well as, the collection you are querying against. e.g.:

MongoCursor<Email> csr

Cheers!

Upvotes: 1

Related Questions