Dheeraj Palagiri
Dheeraj Palagiri

Reputation: 1879

C# Linq Driver to mongoDB - Bson Array

My document structure contains one field as Bson Array.

I want to get all records from collection with all the Bson array values as List of Strings.

I know the below code is wrong as I am only getting first value of the Bson Array

 public List<String> GetRecordsfromTime(DateTime dateTime)
            {
                return _collection.AsQueryable<SocialRecord>().Where(x => x.DateCreated > dateTime).Select(x => x.TermMonitorIds[1].ToString()).ToList();
            }

Could some one know how to iterate through those bson array to get everything as list of strings.

Upvotes: 0

Views: 1766

Answers (2)

Cameron
Cameron

Reputation: 2594

You're using an indexer on your TermMonitorIds collection, so you're getting the second element of every collection of TermMonitorIds in your SocialRecord collection.

You'll want to instead do a SelectMany like so:

return _collection.AsQueryable<SocialRecord>()
                  .Where(x => x.DateCreated > dateTime)
                  .SelectMany(x => x.TermMonitorIds.ToString())
                  .ToList();

Edit: Since OP has said MongoDB doesn't allow SelectMany query operators.

// Evaluate the query
var socialRecords = _collection.AsQueryable<SocialRecord>()
                               .Where(x => x.DateCreated > dateTime)
                               .ToList();

// Return desired results.
return socialRecords.SelectMany(x => x.TermMonitorIds.ToString());

Upvotes: 2

Dheeraj Palagiri
Dheeraj Palagiri

Reputation: 1879

I used the below code to solve this:

 return _collection.AsQueryable<SocialRecord>()
                           .Where(x => x.DateCreated > dateTime)
                           .Select(z => z.TermMonitorIds.Select(x => x.ToString()).ToList())
                           .ToList()
                           .SelectMany(x => x)
                           .ToList();

Upvotes: 0

Related Questions