猿问

如何使用 C# 查询 MongoDB 集合中的数组内部?

我正在尝试遍历以下形式的 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();

预期结果:具有匹配数组的所有文档


当前输出:错误


任何帮助我应该如何进行。


素胚勾勒不出你
浏览 110回答 2
2回答

凤凰求蛊

使用MongoDb.Driver 包的基本示例。您需要定义一些数据类型,例如:// Use [BsonIgnoreExtraElements] attribute when not defining ALL fields in recordinternal class MainRecord{&nbsp; &nbsp; public ObjectId _id { get; set; }&nbsp; &nbsp; public List<ArrayItem> ResourceStatus { get; set; }&nbsp; &nbsp; // All the other fields here}// [BsonIgnoreExtraElements] as aboveinternal class ArrayItem{&nbsp; &nbsp; 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);编辑:我建议查看这篇文章,它提供了一些替代方法。

Cats萌萌

我创建简单的类来演示如何:MongoDB 类public class MongoDBConnect : IDisposable{&nbsp; &nbsp; public IMongoClient client;&nbsp; &nbsp; public IMongoDatabase database;&nbsp; &nbsp; public MongoDBConnect()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; client = new MongoClient("mongodb://localhost");&nbsp; &nbsp; &nbsp; &nbsp; database = client.GetDatabase("dbo");&nbsp; &nbsp; }&nbsp; &nbsp; public void Dispose()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; GC.WaitForPendingFinalizers();&nbsp; &nbsp; &nbsp; &nbsp; GC.Collect();&nbsp; &nbsp; }}你的收藏课public class YourCollection{&nbsp; &nbsp; [BsonId()]&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; public ObjectId Id { get; set; }&nbsp; &nbsp; [BsonElement("YourCollectionID")]&nbsp; &nbsp; public string YourCollectionID { get; set; }&nbsp; &nbsp; [BsonElement("AccessKey")]&nbsp; &nbsp; public string AccessKey { get; set; }}您的集合数据类public class YourCollectionDAO : MongoDBConnect{&nbsp; &nbsp; public YourCollectionDAO()&nbsp; &nbsp; {&nbsp; &nbsp; }&nbsp; &nbsp; public YourCollection Find(string yourCollectionID)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var collection = this.database.GetCollection<User>("YourCollection");&nbsp; &nbsp; &nbsp; &nbsp; Expression<Func<YourCollection, bool>> filter = x => x.yourCollectionID == yourCollectionID;&nbsp; &nbsp; &nbsp; &nbsp; IList<YourCollection> filtering = collection.Find(filter).ToList();&nbsp; &nbsp; &nbsp; &nbsp; var yourCollectionItem = filtering.Where(x => x.yourCollectionID == yourCollectionID).FirstOrDefault();&nbsp; &nbsp; &nbsp; &nbsp; return yourCollectionItem;&nbsp; &nbsp; }}希望能帮助到你。
随时随地看视频慕课网APP

相关分类

Go
我要回答