2017-12-07 21 views
0

cはMongoDBの内の1つの配列にコレクションのすべてのネストされた配列に参加しますは、私がこのような構造を持つ文書を持っている#

["111111111111111111111111","222222222222222222222222","333333333333333333333333","444444444444444444444444"] 

さて、私はMongoDB.Dを使用して、次のようにやっている:私はのような配列がしたい

{ 
     "_id" : ObjectId("5a26f1764cacd91bf4624a76"), 
     "CompetitorIds" : [ 
      "111111111111111111111111", 
      "222222222222222222222222" 
     ], 
     "BusinessId" : "5a1bfcac2b8fb6096885cbb8" 
    } 
    { 
     "_id" : ObjectId("7a26f1764cacd91bf4112a88"), 
     "CompetitorIds" : [ 
      "333333333333333333333333", 
      "444444444444444444444444" 
     ], 
     "BusinessId" : "5a1bfcac2b8fb6096885cbb8" 
    } 

川からC#:

public class Product 
{ 
    public ObjectId Id { get; set; } 
    public string[] CompetitorIds { get; set; } 
    public string BusinessId { get; set; } 
} 

public List<string> GetAllCompetitors(string businessId) 
{    
    var builder = Builders<Product>.Filter; 
    var filter = builder.Eq(p => p.BusinessId, businessId) & builder.Where(p => p.CompetitorIds.Length > 0); 
    var collection = _collection.Find(filter); 
    var productIdsAlreadyBound = collection.ToList().SelectMany(x => x.CompetitorIds).ToList(); 
} 

しかし、私はそれを行うより良い方法があるかどうかを知りたいと思います。助言がありますか?

+1

'VAR productIdsAlreadyBound = _collection.Distinct( "competitorIds"、フィルタ)試してみてください;'や 'のFieldDefinition フィールド= "CompetitorIdsを"。 var productIdsAlreadyBound = _collection.Distinct(field、filter); ' – Veeram

+0

@Veeram動作しませんでした。 –

+0

@Veeramが提供している例では、 "CompetitorIds"の末尾のスペースを必ず削除してください。また、小文字のバージョンを使用する必要があるかもしれません。なぜなら、C#の表現に合わせるために変更する前に、サンプルデータが含まれているからです。 – dnickless

答えて

0

編集:コメントは次のように@ Veeramの解答が上手くなります。ここで

は、あなたがそれを行うことができる方法である。

まず、あなたは(必須)$unwind段階の後、あなたの文書構造を表しタイプを定義します。このタイプでは、C#クライアントを扱うのが面白くなりますので、stringで手を加えずに、型付きコードを書くことができます。

public class ProductAfterUnwind 
{ 
    public string CompetitorIds { get; set; } 
} 

そして、あなたがこれを行うことができます。

var productIdsAlreadyBound = _collection 
    .Aggregate() 
    .Match(p => p.BusinessId == "5a1bfcac2b8fb6096885cbb8") 
    .Unwind<Product, ProductAfterUnwind>(p => p.CompetitorIds) 
    .Group(p => string.Empty, grouping => new 
    { 
     CompetitorIds = grouping.Select(p => p.CompetitorIds).Distinct() 
    }) 
    .FirstOrDefault(); 
+0

これはうまくいきませんでした。空のリストがありました。 –

+0

これは、上記の私のコメントを参照してください。 "competitorIds" - 追加マッピングなしでは、私のコードは大文字のバージョンを前提としています。 – dnickless

関連する問題