1
votes

I need to first find the document by _id. Then in the document to find subdocument which have a Time field is greater than the parameter lastTime

var filter = builder.Eq("_id", symbol) & builder.Gt("Update.Time", lastTime);
var result = await MongoDb.CollectionName.Find(filter).ToListAsync();

This example has a result of 0.

How to write this query? I need get this subdocument "Update" or last 3 sub-subdocument

The document has the following structure

{
  {"_id", symbol},
  {"Update", [
              {"_id", number}, {"Time", sometime}, {"Version", versionNumber}, 
              {"_id", number}, {"Time", sometime}, {"Version", versionNumber},
              {"_id", number}, {"Time", sometime}, {"Version", versionNumber},
              {"_id", number}, {"Time", sometime}, {"Version", versionNumber},}
             ]
}
2

2 Answers

0
votes

If mongodb console will work an example:

> db.doc.save({
   "_id":"123", 
   "update":[
       {"_id":'1', "time":'345', "Version":'3'}, 
       {"_id":'2', "time":'234', "Version":'4'}
    ]
})
> db.doc.findOne( { _id:"123", "update.time":{ $gt: 344 } } )

Then for C# Will can you to try ?

var collection = _database.GetCollection<BsonDocument>("name");
var filter = Builders<BsonDocument>.Filter.Gt("update.time", 344);
var result = await collection.Find(filter).ToListAsync();

This example

UPD This can be:

var collection = _database.GetCollection<BsonDocument>("name");
var builder = Builders<BsonDocument>.Filter;
var filter  = builder.Eq("_id", id) & builder.Gt("update.time", 344);
var result  = await collection.Find(filter).ToListAsync();
-1
votes

Try using lambda expressions:

var lastTime = 1;
var result = collection.Find(x => x.Update.Contains(lastTime));