使用字典<string,list <string =“” >>构建$或查询

时间:2018-11-04 22:25:55

标签: c# mongodb linq mongodb-query

我在这里苦苦挣扎。我是刚开始在mongo中进行任何复杂操作的新手。

在mongo中提供以下文档:

{ Id = 1, SharedId = "K1", Tag = "V1" }
{ Id = 2, SharedId = "K1", Tag = "V2" }
{ Id = 3, SharedId = "K1", Tag = "V3" }
{ Id = 4, SharedId = "K2", Tag = "V1" }
{ Id = 5, SharedId = "K2", Tag = "V2" }
{ Id = 6, SharedId = "K2", Tag = "V3" }

我有一个方法GetRecords(Dictionary<string, List<string>> docs),其键为SharedId,并且列表包含Tags的列表。示例:

[
    { "K1", [ "V1", , "V3" ] },
    { "K2", [ "V2", "V3" ] }
]

我想提取以下记录:

1, 3, 5, 6

我当前的方法如下。

GetRecords(Dictionary<string, List<string>> docs)
{
    var filter = Builders<Dto>.Filter.Where(d =>
        !string.IsNullOrEmpty(d.SharedId) &&
        docs.Keys.Contains(d.SharedId))
}

尝试用我正在使用的东西做进一步的尝试,会从mongo抛出很多错误,通常是NotSupported等。docs[d.SharedId].Any(i => docs.Contains(i))之类的东西使mongodriver很不高兴。

1 个答案:

答案 0 :(得分:2)

从问题的表达方式来看,您是否想要这样的结构(显示序列化的JSON形式)还不清楚:

{ "K1": [ "V1", "V3" ], "K2": [ "V2", "V3" ] } 

或者这样:

[
  { "K1": [ "V1", "V3" ] },
  { "K2": [ "V2", "V3" ] }
]

无论哪种方式,您基本上都是在迭代单个字典的键/值对,或者对于“字典列表”几乎相同。

最终结果意味着从任何一种初始形式构建这样的查询:

      {
        "$or" : [
            {
              "SharedId" : "K1",
              "Tag" : { "$in" : [ "V1", "V3" ] }
            },
            {
              "SharedId" : "K2",
              "Tag" : { "$in" : [ "V2", "V3" ] }
            }
        ]
      }

执行此操作的基本方法是使用foreach迭代并列出FilterDefinition的列表,然后将其提供给Builders<T>.Filter.Or

具有以下代码的示例清单:

using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
  class Program
  {
    static void Main(string[] args)
    {
      MainAsync().Wait();
    }

    static async Task MainAsync()
    {
      var client = new MongoClient();
      var db = client.GetDatabase("test");
      var entities = db.GetCollection<Entity>("entities");

      try
      {
        /*
         * Meaning a serialized structure like:
         * { "K1": [ "V1", "V2" ], "K2": [ "V2", "V3" ] } 
         */
        Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>
        {
          { "K1", new List<string> { "V1", "V3" } },
          { "K2", new List<string> { "V2", "V3" } }
        };

        string output = JsonConvert.SerializeObject(dict);
        Console.WriteLine(output);

        /*
         *  Meaning a serialized structure like:
         *  [
         *    { "K1": [ "V1", "V2" ] },
         *    { "K2": [ "V2", "V3" ] }
         *  ]
         */
        List<Dictionary<string, List<string>>> alt = new List<Dictionary<string, List<string>>>
        {
          {  new Dictionary<string, List<string>> { { "K1", new List<string> {  "V1", "V3" } } } },
          {  new Dictionary<string, List<string>> { { "K2", new List<string> {  "V2", "V3" } } } },
        };

        string output2 = JsonConvert.SerializeObject(alt);
        Console.WriteLine(output2);

        // Build query from 'dict' form
        List<FilterDefinition<Entity>> orConditions = new List<FilterDefinition<Entity>>();
        foreach (KeyValuePair<string, List<string>> entry in dict)
        {
          orConditions.Add(
            Builders<Entity>.Filter.Eq(p => p.SharedId, entry.Key) &
            Builders<Entity>.Filter.Where(p => entry.Value.Contains(p.Tag))
          );
        };
        var query1 = Builders<Entity>.Filter.Or(orConditions);
        /*
         * Builds -
          {
            "$or" : [
                {
                  "SharedId" : "K1",
                  "Tag" : { "$in" : [ "V1", "V3" ] }
                },
                {
                  "SharedId" : "K2",
                  "Tag" : { "$in" : [ "V2", "V3" ] }
                }
            ]
          }
        */
        Console.WriteLine("Output 1");
        var cursor1 = await entities.Find(query1).ToListAsync();
        foreach (var doc in cursor1)
        {
          Console.WriteLine(doc.ToBsonDocument());
        }

        // Build the query from 'alt' form
        orConditions = new List<FilterDefinition<Entity>>(); // clear the list

        foreach(var item in alt)
        {
          foreach(KeyValuePair<string,List<string>> entry in item)
          {
            orConditions.Add(
              Builders<Entity>.Filter.Eq(p => p.SharedId, entry.Key) &
              Builders<Entity>.Filter.Where(p => entry.Value.Contains(p.Tag))
            );
          }
        }

        var query2 = Builders<Entity>.Filter.Or(orConditions);

        /* Serializes just the same */
        Console.WriteLine("Output 2");
        var cursor2 = await entities.Find(query2).ToListAsync();
        foreach (var doc in cursor2)
        {
          Console.WriteLine(doc.ToBsonDocument());
        }


      }
      catch (Exception ex)
      {
        Console.WriteLine(ex);
      }

    }
  }

  public class Entity
  {
    public int id;
    public string SharedId { get; set; }
    public string Tag { get; set; }
  }
}

这显示了从任一数据结构形式到同一查询的转换,并返回了预期的文档:

{"K1":["V1","V3"],"K2":["V2","V3"]}
[{"K1":["V1","V3"]},{"K2":["V2","V3"]}]
Output 1
{ "_id" : 1, "SharedId" : "K1", "Tag" : "V1" }
{ "_id" : 3, "SharedId" : "K1", "Tag" : "V3" }
{ "_id" : 5, "SharedId" : "K2", "Tag" : "V2" }
{ "_id" : 6, "SharedId" : "K2", "Tag" : "V3" }
Output 2
{ "_id" : 1, "SharedId" : "K1", "Tag" : "V1" }
{ "_id" : 3, "SharedId" : "K1", "Tag" : "V3" }
{ "_id" : 5, "SharedId" : "K2", "Tag" : "V2" }
{ "_id" : 6, "SharedId" : "K2", "Tag" : "V3" }