1

I have got a class called Contact which has a field named Numbers and Numbers is a list of strings. I want to return a list containing all numbers in matched documents only. but it gives me an array of BsonDocuments. I need Just a List of numbers.

here is my query:

var query = await _context.ContactLists.Aggregate(new AggregateOptions { AllowDiskUse = true })
                    .Match(x => x.Id == id && x.CreatorId == user.GetUserId())
                    .Unwind(x => x.Numbers)
                    .Project(Builders<BsonDocument>.Projection.Include("Numbers").Exclude("_id"))
                    .ToListAsync();

it resturns :

[{{ "Numbers" : "989309910790" }}]

and I need :

["989309910790"]

I am not allowed to use Linq driver.

Daviid
  • 35
  • 5
  • 1
    mostlikely it's unrelated to LINQ provider, check what you expect to see with a shell and `$unwind`: https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/, I think you will see the same result – dododo Aug 15 '21 at 16:56
  • @dododo Thanks , I checked it out. but in all examples unwind returns array of objects. i need array of values. perhaps it could be possible with a projection stage. but I don't how to do it. I've been always using Linq driver and not so familiar with bsonDocument queries. – Daviid Aug 15 '21 at 19:33
  • 1
    I think it should be done via projection, try to play with samples here https://docs.mongodb.com/manual/reference/operator/aggregation/project/ – dododo Aug 15 '21 at 19:55
  • 1
    also you may try to look at aggregate `select` LINQ method, for example like here: https://mongodb.github.io/mongo-csharp-driver/2.13/reference/driver/crud/linq/ – dododo Aug 15 '21 at 19:59
  • @dododo , I used LINQ provider: `var data = _context.ContactLists.AsQueryable().Where(x =>.....).SelectMany(x => x.Numbers).ToList();` which gives me correct answer. and noticed the translated query. `{aggregate([{ "$match" : { "_id" : ObjectId("61168db3b967a2bdd1967302"), "CreatorId" : "60e5b8bb697a33a84ddb9ce7" } }, { "$unwind" : "$Numbers" }, { "$project" : { "Numbers" : "$Numbers", "_id" : 0 } }])} ` So how is it different from my original query ? – Daviid Aug 16 '21 at 05:18
  • Actually , the real question is : How can we tell Mongodb, Not to return a BsonDocument but returns the values only ? in this case, an array of strings, not array of **key,value pair** json. – Daviid Aug 16 '21 at 06:11
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/236036/discussion-between-daviid-and-dododo). – Daviid Aug 16 '21 at 06:36

0 Answers0