亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 C# 查詢 MongoDB 集合中的數組內部?

如何使用 C# 查詢 MongoDB 集合中的數組內部?

Go
素胚勾勒不出你 2022-11-21 20:13:10
我正在嘗試遍歷以下形式的 MongoDB 集合:{"_id":"lkashfhasdfhsdlafhlkjsdahf",""Array":[{                    "array_1":"17:00"}],}我想在上面的文檔中獲取 array_1 我在C#中使用以下代碼嘗試過result = Database.CollectionName.AsQueryable().Where(r => r.Array.array== array_inpit(Input) && condition2).ToList();預期結果:具有匹配數組的所有文檔當前輸出:錯誤任何幫助我應該如何進行。
查看完整描述

2 回答

?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

使用MongoDb.Driver 包的基本示例。您需要定義一些數據類型,例如:


// Use [BsonIgnoreExtraElements] attribute when not defining ALL fields in record

internal class MainRecord

{

    public ObjectId _id { get; set; }


    public List<ArrayItem> ResourceStatus { get; set; }


    // All the other fields here

}


// [BsonIgnoreExtraElements] as above

internal class ArrayItem

{

    public string E2EId { get; set; }

}

(注意——我省略了數組搜索不需要的所有字段)。


然后實際查詢數據:


var client = new MongoClient();


IMongoDatabase db = client.GetDatabase("database-name-here");


var collectionName = "collection-name-here";


IMongoCollection<MainRecord> collection = db.GetCollection<MainRecord>(collectionName);


var filter = Builders<MainRecord>.Filter.ElemMatch(x => x.ResourceStatus, x => x.E2EId == "1fdsfsfsfsfsffds0");


var result = collection.Find(filter);

編輯:我建議查看這篇文章,它提供了一些替代方法。


查看完整回答
反對 回復 2022-11-21
?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

我創建簡單的類來演示如何:


MongoDB 類


public class MongoDBConnect : IDisposable

{

    public IMongoClient client;

    public IMongoDatabase database;


    public MongoDBConnect()

    {

        client = new MongoClient("mongodb://localhost");

        database = client.GetDatabase("dbo");

    }


    public void Dispose()

    {

        GC.WaitForPendingFinalizers();

        GC.Collect();

    }

}

你的收藏課


public class YourCollection

{

    [BsonId()]        

    public ObjectId Id { get; set; }


    [BsonElement("YourCollectionID")]

    public string YourCollectionID { get; set; }


    [BsonElement("AccessKey")]

    public string AccessKey { get; set; }

}

您的集合數據類


public class YourCollectionDAO : MongoDBConnect

{

    public YourCollectionDAO()

    {


    }


    public YourCollection Find(string yourCollectionID)

    {

        var collection = this.database.GetCollection<User>("YourCollection");


        Expression<Func<YourCollection, bool>> filter = x => x.yourCollectionID == yourCollectionID;


        IList<YourCollection> filtering = collection.Find(filter).ToList();


        var yourCollectionItem = filtering.Where(x => x.yourCollectionID == yourCollectionID).FirstOrDefault();


        return yourCollectionItem;

    }

}

希望能幫助到你。


查看完整回答
反對 回復 2022-11-21
  • 2 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號