alp_the_developer
alp_the_developer

Reputation: 785

Get last N items on collection

i'm trying mongo db. i need to get last 5 or 10 elements from a collection.

i need to use that query in mongodb:

SELECT * FROM records ORDER BY id DESC LIMIT 10

also if possible,

SELECT * FROM records WHERE value = 'myValue' ORDER BY id DESC LIMIT 10

how can i do this in c# and mongodb ?

Upvotes: 0

Views: 1927

Answers (2)

RizJa
RizJa

Reputation: 2031

Mongo Shell:

/* 1 */ db.MyCollection.find({}).sort({ _id: -1 }).limit(10)
/* 2 */ db.MyCollection.find({ value: 'myValue' }).sort({ _id: -1 }).limit(10)

C# Mongo Driver:

MongoClient mongoClient = new MongoClient(mongoConnString);
IMongoDatabase mdb = mongoClient.GetDatabase(dbName);
IMongoCollection<MyCollection> coll = mdb.GetCollection<MyCollection>(myCollection);

var sort = Builders<MyCollection>.Sort.Descending("_id");
var filter1 = Builders<MyCollection>.Filter.Empty;
var filter2 = Builders<MyCollection>.Filter.Eq("value", "myValue");

/* 1 */ var results = coll.Find(filter1).Sort(sort).Limit(10);
/* 2 */ var results = coll.Find(filter2).Sort(sort).Limit(10);

Note that I'm assuming id in your SQL query refers to an Identity column. The Mongo equivalent would be _id.

Upvotes: 2

Julien TASSIN
Julien TASSIN

Reputation: 5212

assuming you have an indexed dt field in your records :

db.collection.find({value: 'myValue'}).sort({dt: -1})

Without dt field, you can also do :

db.collection.find({value: 'myValue'}).sort({_id: -1})

Upvotes: 0

Related Questions