简体   繁体   中英

Comparing two fields of mongo collection using c# driver in mono

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

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.

There is another way to do it. First lets declare collection:

var collection = Database.GetCollection<BsonDocument>("CollectionName");

Now lets add our project:

var pro = new BsonDocument {
                {"gt1", new BsonDocument {
                    { "$gt", new BsonArray(){ "$LastModifiedAt", "$LastSyncedAt" }
                    }
                } },
                {"Name", true },
                {"LastModifiedAt", true },
                {"LastSyncedAt", true }
                };

Now lets add our filter:

var filter = Builders<BsonDocument>.Filter.Eq("gt1", true);

We'll aggregate our query:

var aggregate = collection.Aggregate(new AggregateOptions { AllowDiskUse = true })
                .Project(pro)
                .Match(filter)

Now our query is ready. We can check our query as follow:

var query=aggregate.ToString();

Lets run our query as follow:

var query=aggregate.ToList();

This with return the required data in list of bson documents.

This solution will work mongo c# driver 3.6 or above. Please comment in case of any confusion. Hopefully i'll able to explain this.

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