Jubish Kammily
Jubish Kammily

Reputation: 129

MongoDB Last value or Max value using C#

I am facing issues in retrieving the Latest value from the MongoDB table (Collection).

My table doesn't have a class mapped. I cannot create a class for my table due to the dynamic behaviour.

For Eg MyTable has 4 columns mentioned below is the table and values.

Id , DateTime,  Column1, Column2

1     somTime     1         1
2     somTime     2         2
3     somTime     3  

Due to the user requirements the table is dynamic, the user can create as many columns he want and he can insert values in to these columns separately. In this I want to get the latest value inserted in the Column2 which is 2.

My code looks like this.

var maxDateTime = (from collect in document.AsQueryable()
                   select collect["dateTime"]).Max();

var qLatestValue = Query.EQ("DateTime", maxDateTime);
value = result["Column1"];   
// this works fine since the Column1 exists

value = result["Column2"];

// this code is giving exception

The Column2 is not present in the document retrieved. Due to this its throwing keynotFound exception.

How to get the latest value of this Column2? Can any one please help in this?

Upvotes: 0

Views: 306

Answers (3)

Jubish Kammily
Jubish Kammily

Reputation: 129

Sorry for the late reply. Below code fixed my issue.

var maxDateTime =(from a in document.AsQueryable() where c[columnName] != BsonNull.Value select c["DateTime"]).Max();

var qlatest= Query.EQ("DateTime", maxDateTime);
var result = document.FindOne(qlatest);
value = result[columnName];

Upvotes: 0

Disposer
Disposer

Reputation: 6371

Your result doesn't have a filed named Column2 in your document. The solution is getting value via

Way 1:

result["Column2", BsonNull.Value]

Way 2:

result.GetValue("Column2", BsonNull.Value);

Way 3:

BsonValue value;
var hasValue = doc.TryGetValue("Column2");

Upvotes: 1

Kevin Brady
Kevin Brady

Reputation: 1724

When you are retrieving the maxDateTimevalue you are retrieving the most recent one in the collection but this document may not contain the Column2 key

You will need to include a Where clause in your maxDateTime query any only get the maxDateTime for documents where the Column2 key exists.

e.g

Query.Exists("Column2")

Upvotes: 0

Related Questions