0

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.

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, exactly what I neded. Thanks Johny
0

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

3 Comments

I want to do it that way because I want to get myself familiar with one way of querying instead of diving into Linq, which I have no experience with. An example of Linq of how to achieve it would be educational though.
That's the difference, Linq will be same for different things, not only mongooDB. Any case, I suppose you map this to classes with attributes with the same names so it will be something like collection.AsQueryable<YourClass>(). Where(c=>c.Id==10 && c=>c.planet_sizes.Any(ps=>ps.Id==1));
Now that I read, I think that the C# query you make is exactly what the mongo shell does too, but for the explanation of what you want it is not what you are looking for. From the mongodb documentation of elemMatch "The $elemMatch operator matches documents in a collection that contain an array field with at least one element that matches all the specified query criteria." So it will return all docs with id 10 that at least have 1 element in planet_sizes with id equals to 1. It is not going to filter those planet_sizes with different id from the main doc

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.