簡體   English   中英

如何獲取 MongoDB 中的最后 n 個子文檔?

[英]How to get last n subdocument in MongoDB?

我想找到一個 Id=A 的文檔,然后對文檔 A 中的子文檔進行排序。但我找不到任何解決方案,尤其是在 c# 的 MongoDB.Driver 中。 在文檔級別,我們有這樣的查詢:

db.foo.find().sort({_id:1}).limit(50);

但是我需要對子文檔而不是文檔應用限制 function。

以 model 為例:

{
"_id" : "10000",
"password" : "password1",
"name" : "customer1",
"channels" : [ 
    {
        "id" : "1",
        "name" : "cust1chan1",
        "enabled" : true
    }, 
    {
        "id" : "2",
        "name" : "cust1chan2",
        "enabled" : true
    }, 
    {
        "id" : "3",
        "name" : "cust1chan2",
        "enabled" : true
    }, 
    {
        "id" : "4",
        "name" : "cust1chan2",
        "enabled" : true
    },...
]}

我喜歡我的結果與此類似:

{
"_id" : "10000",
"password" : "password1",
"name" : "customer1",
"channels" : [ 
    {
        "id" : "1",
        "name" : "cust1chan1",
        "enabled" : true
    }, 
    {
        "id" : "2",
        "name" : "cust1chan2",
        "enabled" : true
    }
]}

我找到了解決方案。 我們可以在 Projection 中使用 Slice function。 像這樣的東西:

            var filter = Builders<Foo>.Filter.Where(p => p.Id == fooId);
            var slice = Builders<Foo>.Projection.Slice(p => p.Channels, 0, 2);
            var sort = Builders<Foo>.Sort.Descending("Foo.Channels");
            var articleDocument = _collectionFoo.Find(filter).Sort(sort).Project<Foo>(slice).FirstOrDefault();

暫無
暫無

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

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