Question

I'm using C# mongo driver and I have users collection like below,

 public class User
{
    public string Name { get; set; }

    public DateField Date { get; set; }

    /*
     * Some more properties
     */

    public List<string> Slugs { get; set; } //I just need to return this property

}

I'm writing a query in which it just returns me the slugs property. To do this i'm trying to use SetFields(...) method from the mongo driver. SetFields returns the cursor of the User type i'm expecting something to be of my Slugs property type so that I don't return whole set of properties when i just need one. Is it possible ?

Was it helpful?

Solution

Yes and no. You can use the aggregation framework's projection operator $project to change the structure of the data, but I wouldn't do that for two reasons:

  1. MongoDB generally tries to preserve the structure unless you force it to, particularly because it makes it easier to work with statically typed languages (the old object/relational mismatch: SQL queries don't 'answer' in users or blog post, but some wild Chimaera of properties collected from various tables, which might require additional DTOs depending on the query itself, which is all a bit ugly).
  2. Aggregation framework queries are a bit more complicated and a bit slower, and I wouldn't let the urge to do some micro-optimization dictate a lot of unnecessary complexity.

After all, omitting a few fields is a micro-optimization already (setting index covered queries aside), but on the client-side the cost of empty fields should be next to none.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top