簡體   English   中英

使用 C# 和 MongoDriver 從 MongoDB 中的文檔數組中過濾文檔

[英]Filtering documents from document array in MongoDB with C# and MongoDriver

我有一個 MongoDB(在 Cosmos DB 上運行),並試圖根據列表過濾掉數組中的子文檔。 我在 Mongo Shell 中取得了一些成功,但我沒有達到我的目標,並且在使用 MongoDriver 的 C# 中沒有成功。

我想要做的是例如在我的數據庫中給出這兩個文檔:

{
    "person" : "John",
    "pet" : [
        {
            "name" : "Spot",
            "type" : "Dog"
        },
        {
            "name" : "Ms. Whiskers",
            "type" : "Cat"
        },
        {
            "name" : "Jack",
            "type" : "Hamster"
        }
    ]
},
{
    "person" : "Jane",
    "pet" : [
        {
            "name" : "Max",
            "type" : "Lizard"
        }
    ]
}

我想過濾掉類型既不是狗也不是倉鼠的寵物子文檔。

{
    "person" : "John",
    "pet" : [
        {
            "name" : "Ms. Whiskers",
            "type" : "Cat"
        }
    ]
},
{
    "person" : "Jane",
    "pet" : [
        {
            "name" : "Max",
            "type" : "Lizard"
        }
    ]
}

我最接近的是以下 Shell 命令作為 $nin 未知操作員錯誤。

db.collection.aggregate([{ 
    $project: {
        pet: {
            $filter: {
                input: "$pet", 
                as: "p",
                cond: {$ne: [ "$$p.type", "dog" ]}
            }
        }
    }
}
]).pretty()

但我不知道如何將其轉換為 C# Mongo 驅動程序查詢,有人可以幫忙嗎?

Cosmos 模擬版本 3.6 MongoDB,如果這對我的方案有任何影響,它的版本剛剛升級到 4.0。 我正在使用 MongoDriver v2.12.2 和 .NET Core 3.1

首先,您需要使pet屬性IEnumerable<T>像這樣:

public class item : Entity
{
    public IEnumerable<pet> pet { get; set; }
}

然后您可以使用Queryable接口過濾掉不需要的類型,如下所示:

var result = await collection
    .AsQueryable()
    .Select(x => new item
    {
        person = x.person,
        pet = x.pet.Where(p => p.type != "Dog" && p.type != "Hamster")
    })
    .ToListAsync();

或者您可以將排除項設置為字符串數組並更改 where 子句,如下所示:


var excludes = new[] { "Dog", "Hamster" };

var result = await collection
    .AsQueryable()
    .Select(x => new item
    {
        person = x.person,
        pet = x.pet.Where(p => !excludes.Contains(p.type))
    })
    .ToListAsync();

暫無
暫無

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

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