简体   繁体   中英

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 ?

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 .

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})

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