1

I working with MongoDB driver and I have the following classes:

public class Transactions
{
    public ObjectId Id { get; set; }
    public int UserId { get; set; }
    public int AccountId { get; set; }
    public int SettingId { get; set; }
}
public class Account
{
    public int Id {get; set;}
    public int Name {get; set;}
}
public class User
{
    public int Id {get; set;}
    public int Name {get; set;}
}
public class Setting
{
    public int Id {get; set;}
    public int Name {get; set;}
}

And I want form this, depending of the input of user:

var docs = collection.Aggregate()
                     .Lookup("account", "AccountId", "_id", "asAccounts")
                     .Lookup("user", "UserId", "_id", "asUsers")
                     .Lookup("setting", "SettingId", "_id", "asSettings")
                     .As<BsonDocument>()
                     .ToList();

That is, if the user just wanna the relation with account, form this:

var docs = collection.Aggregate()
                         .Lookup("account", "AccountId", "_id", "asAccounts")
                         .As<BsonDocument>()
                         .ToList();

Or if him wanna the relation with account and user:

var docs = collection.Aggregate()
                         .Lookup("user", "UserId", "_id", "asUsers")
                         .Lookup("setting", "SettingId", "_id", "asSettings")
                         .As<BsonDocument>()
                         .ToList();

It I trying to do is form the query depending the needs of user. Just wanna know how to chain the methods in runtime.

Carlos Herrera
  • 325
  • 1
  • 6

1 Answers1

0

You can create your dynamic chain using some conditional tests to prepare the query:

var docs = collection.Aggregate();

if ( WantRelationWithAccount )
  docs = docs.Lookup("account", "AccountId", "_id", "asAccounts")

if ( WantRelationWithUser )
  docs = docs.Lookup("user", "UserId", "_id", "asUsers")

if ( WantSettings )
  docs = docs.Lookup("setting", "SettingId", "_id", "asSettings")

var result = docs.As<BsonDocument>().ToList();

But remember that order of operations in the chain is as added.

Linq queries are deferred executed, that means they are only executed when used like with a loop or a any method that causes the execution like ToList.

There is a linq ToLookup method but not Lookup, and it causes the query execution.

Does ToLookup forces immediate execution of a sequence

Perhaps you use extension methods provided by a special framework.

In anyway, staging execution does not prevent you from create the chain as exposed previously.

  • 1
    I'm thinking that `Aggregate` and `Lookup`, which have meaning in Mongo, are methods that come with the MongoDB driver. Which makes me wonder: they look fluent, but is their execution truly deferred? – Ann L. Jul 12 '20 at 17:16