簡體   English   中英

獲取集合中的最后N個項目

[英]Get last N items on collection

我正在嘗試mongo db。 我需要從集合中獲取最后5或10個元素。

我需要在mongodb中使用該查詢:

SELECT * FROM records ORDER BY id DESC LIMIT 10

如果可能的話

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

我如何在c#和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驅動程序:

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

請注意,我假設您的SQL查詢中的id引用一個Identity列。 相當於Mongo的是_id

假設您的記錄中有一個索引dt字段:

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

沒有dt字段,您還可以執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM