简体   繁体   中英

Get all records with inner record from last month - MongoDB C# SDK

I'm trying to get all the users that had any kind of activity in the last month from my MongoDB database, using C# SDK.

My User record contains a list of statistical records (as ObjctId) with creation date.

public class UserRecord
{
    private string firstName;

    public ObjectId Id
    {
        get;
        set;
    }

    public List<ObjectId> Statistics
    {
        get;
        set;
    }
}

And my query builder function looks like this:

static IMongoQuery GenerateGetLiveUsersQuery(DateTime lastStatistic)
{
        List<IMongoQuery> queries = new List<IMongoQuery>();

        queries.Add((Query<UserRecord>.GTE(U =>
             U.Statistics.OrderByDescending(x => x.CreationTime).First().CreationTime
               , lastStatistic)));

          ///.... More "queries.Add"...

        return Query.And(queries);           
}

Not sure what I'm doing wrong but I get en System.NotSupportedException error message while trying to build the query (the GTE query).

Unable to determine the serialization information for the expression: (UserRecord U) => Enumerable.First(Enumerable.OrderByDescending(U.Statistics, (ObjectId x) => x.CreationTime)).CreationTime.

The following query should work

var oId = new ObjectId(lastStatistic, 1, 1, 1);
var query = Query<UserRecord>.GTE(e => e.Statistics, oId);

you can create an ObjectId based on the lastStatistic Date which is your cut-off. Then you can just query the UserRecord collection to find any records that have an item in the Statistics list that is greater than your ObjectId .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM