简体   繁体   中英

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.

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());

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM