Home How to apply filter on Array object in MongoDb table using Mongodb.Driver in C#?
Reply: 0

How to apply filter on Array object in MongoDb table using Mongodb.Driver in C#?

user5662
1#
user5662 Published in September 20, 2018, 12:44 pm

I am using MongoDB to store my application data. Now I want to fetch data based on filter on Array object in MongoDB table. as you can see below pic

This is my table tblEmployee. I want to find those records whose GroupList field contains value Group5. When I inserted these records as in mongodb table at that time I stored it as Dictionary<string,dynamic> from C# Code as below.

var clientTest = new MongoClient("mongodb://localhost:XXXX");
var dbTest = clientTest.GetDatabase("Test_DB");
var collectionTest = dbTest.GetCollection<Dictionary<string, dynamic>>("tblEmployee"); 
Dictionary<string, dynamic> obj = new Dictionary<string, dynamic>();
string[] items = { "Group1", "Group2", "Group5", "Group6" };
obj.Add("_id", Guid.NewGuid());
obj.Add("FirstName", "Carlton");
...// Other Props and Values
obj.Add("GroupList", items); // Here value type is String Array.
await collectionTest.InsertOneAsync(obj);

Now, I tried below code read data based on filter as I want.

var clientTest = new MongoClient("mongodb://localhost:XXXX");
                var dbTest = clientTest.GetDatabase("Test_DB");
                var collectionTest = dbTest.GetCollection<Dictionary<string, dynamic>>("tblEmployee");
                var builder = Builders<Dictionary<string, dynamic>>.Filter;
                var filter = builder.AnyIn("GroupList", "Group5"); // Used AnyIn to create IN filter for Array object
                var allDataObj = await collectionTest.FindAsync(filter);
                var allDataList = allDataObj.ToList(); 

But, in allDataList I got no records, it should return one record (record number 4) which I have highlighted in above image.

Please give me suggestions that How to build Filters for Array object which contains specific value(in my case Array which contain "Group5" string)

Any Help or suggestions would be highly appreciated.

Thanks.

share|improve this question

2 Answers 2

active oldest votes
up vote 1 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.347549 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO