Comparing two fields of mongo collection using c#

2019-07-23 19:39发布

问题:

Am completely new to Mongodb and C# driver.

Development is being done using Monodevelop on Ubuntu 14.04 and Mongodb's version is 3.2.10 :

Currently my code has a POCO as below:

public class User
{
    public String Name { get; set;}
    public DateTime LastModifiedAt { get; set;}
    public DateTime LastSyncedAt { get; set;}

     public User ()
    {

    }
}

Have been able to create a collection and also to add users.

How do I find users, whose LastModifiedAt timestamp is greater than LastSyncedAt timestamp ? Did some searching, but haven't been able to find the answer.

Any suggestions would be of immense help

Thanks

回答1:

Actually, it is not very simple. This should be possible with querysuch as :

var users = collection.Find(user => user.LastModifiedAt > user.LastSyncedAt).ToList();

But unfortunetly MongoDriver could not translate this expression. You could either query all Users and filter on the client side:

var users = collection.Find(Builders<User>.Filter.Empty)
                      .ToEnumerable()
                      .Where(user => user.LastModifiedAt > user.LastSyncedAt)
                      .ToList();

Or send json query, because MongoDb itself is able to do it:

var jsonFliter = "{\"$where\" : \"this.LastModifiedAt>this.LastSyncedAt\"}";
var users = collection.Find(new JsonFilterDefinition<User>(jsonFliter))
                      .ToList();

And, yes, you need an Id - Property for your model class, i haven't mentioned it first, because i thought you do have one, just not posted in the question.