Liron Harel
Liron Harel

Reputation: 11247

MongoDB query field selection using C#

How do I transform this MongoDB Query to a C# Equivalent?

db.lists.find({_id: 10}, {planet_sizes: {$elemMatch: {id: 1}}})

I've tried the following without success, which means that it doesn't return the same results as what I get in the shell:

  IMongoQuery searchQuery = Query.And(
             Query.EQ("_id", 10),
             Query.ElemMatch("planet_sizes",
             Query.EQ("id", 1)));

I want query the main list of document and extract the document with _id 10, and from its array, extract the array item with id equals to 1. The MongoDB string query that I provided above works in shell, but I don't know how to write an equivalent one in C#. Thanks in advance.

Upvotes: 0

Views: 1334

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311865

In the C# driver, the field selection is handled by chaining a call to SetFields:

var docs = db.GetCollection("list")
    .Find(Query.EQ("_id", 10))
    .SetFields(Fields.ElemMatch("planet_sizes", Query.EQ("id", 1)))
    .ToList();

Upvotes: 1

Dario Griffo
Dario Griffo

Reputation: 4274

you can always use linq http://docs.mongodb.org/ecosystem/tutorial/use-linq-queries-with-csharp-driver/ or you want only to use MongoQuery?

Upvotes: 0

Related Questions