我怎样才能'和'多$ elemMatch条款与C#和MongoDB? [英] How can I 'AND' multiple $elemMatch clauses with C# and MongoDB?

查看:265
本文介绍了我怎样才能'和'多$ elemMatch条款与C#和MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是10gen的认可C#驱动程序的MongoDB的C#应用​​程序和数据浏览我使用Mongovue

I am using the 10Gen sanctioned c# driver for mongoDB for a c# application and for data browsing I am using Mongovue.

下面是两个样本文档架构:

Here are two sample document schemas:

{
  "_id": {
    "$oid": "4ded270ab29e220de8935c7b"
  },
  "Relationships": [
    {
      "RelationshipType": "Person",
      "Attributes": {        
        "FirstName": "Travis",
        "LastName": "Stafford"
      }
    },
    {
      "RelationshipType": "Student",
      "Attributes": {
        "GradMonth": "",
        "GradYear": "",
        "Institution": "Test1",
      }
    },
    {
      "RelationshipType": "Staff",
      "Attributes": {
        "Department": "LIS",
        "OfficeNumber": "12",
        "Institution": "Test2",
      }
    }
  ]
},    

{
  "_id": {
    "$oid": "747ecc1dc1a79abf6f37fe8a"
  },
  "Relationships": [
    {
      "RelationshipType": "Person",
      "Attributes": {        
        "FirstName": "John",
        "LastName": "Doe"
      }
    },
    {
      "RelationshipType": "Staff",
      "Attributes": {
        "Department": "Dining",
        "OfficeNumber": "1",
        "Institution": "Test2",
      }
    }
  ]
}

我需要确保两个$ elemMatch条件的查询满足这样我可以匹配的第一个文件,而不是第二。 。下面的查询工作在Mongovue

I need a query that ensures that both $elemMatch criteria are met so that I can match the first document, but not the second. The following query works in Mongovue.

{
  'Relationships': { $all: [
        {$elemMatch: {'RelationshipType':'Student', 'Attributes.Institution': 'Test1'}},
        {$elemMatch: {'RelationshipType':'Staff', 'Attributes.Institution': 'Test2'}}
     ]}
}

我如何能做到同样的查询中我的C#代码?

How can I do the same query in my c# code?

推荐答案

我已经解决了通过敷设渠道眼前的问题,允许下面的查询生成一组类的

I have solved the immediate issue by contruction a set of class that allowed for the generation of the following query:

{  'Relationships': 
    { 
        $all: [
         {$elemMatch: {'RelationshipType':'Student', 'Attributes.Institution': 'Test1'}},            
         {$elemMatch: {'RelationshipType':'Staff',   'Attributes.Institution': 'Test2'}}     
        ]
    }
}

下面是类定义:

class MongoQueryAll
    {
        public string Name { get; set; }
        public List<MongoQueryElement> QueryElements { get; set; }

        public MongoQueryAll(string name)
       {
           Name = name;
           QueryElements = new List<MongoQueryElement>();
       }

       public override string ToString()
       {
           string qelems = "";
           foreach (var qe in QueryElements)
              qelems = qelems + qe + ",";

           string query = String.Format(@"{{ ""{0}"" : {{ $all : [ {1} ] }} }}", this.Name, qelems); 

           return query;
       }
  }

class MongoQueryElement
{
    public List<MongoQueryPredicate> QueryPredicates { get; set; }

    public MongoQueryElement()
    {
        QueryPredicates = new List<MongoQueryPredicate>();
    }

    public override string ToString()
    {
        string predicates = "";
        foreach (var qp in QueryPredicates)
        {
            predicates = predicates + qp.ToString() + ",";
        }

        return String.Format(@"{{ ""$elemMatch"" : {{ {0} }} }}", predicates);
    }
}

class MongoQueryPredicate
{        
    public string Name { get; set; }
    public object Value { get; set; }

    public MongoQueryPredicate(string name, object value)
    {
        Name = name;
        Value = value;
    }

    public override string ToString()
    {
        if (this.Value is int)
            return String.Format(@" ""{0}"" : {1} ", this.Name, this.Value);

        return String.Format(@" ""{0}"" : ""{1}"" ", this.Name, this.Value);
    }
}



帮助搜索类别:

Helper Search Class:

public class IdentityAttributeSearch
{
    public string Name { get; set; }
    public object Datum { get; set; }
    public string RelationshipType { get; set; }
}



使用示例:

Example Usage:

 public List<IIdentity> FindIdentities(List<IdentityAttributeSearch> searchAttributes)
 {
        var server = MongoServer.Create("mongodb://localhost/");
        var db = server.GetDatabase("IdentityManager");
        var collection = db.GetCollection<MongoIdentity>("Identities");

        MongoQueryAll qAll = new MongoQueryAll("Relationships");

        foreach (var search in searchAttributes)
        {
            MongoQueryElement qE = new MongoQueryElement();
            qE.QueryPredicates.Add(new MongoQueryPredicate("RelationshipType", search.RelationshipType));
            qE.QueryPredicates.Add(new MongoQueryPredicate("Attributes." + search.Name, search.Datum));
            qAll.QueryElements.Add(qE);
        }

        BsonDocument doc = MongoDB.Bson.Serialization
                .BsonSerializer.Deserialize<BsonDocument>(qAll.ToString());

        var identities = collection.Find(new QueryComplete(doc)).ToList();

        return identities;
    }



我肯定有一个更好的办法,但现在这样工作了,并出现是我需要足够的灵活性。所有建议都欢迎。

I am sure there is a much better way but this worked for now and appears to be flexible enough for my needs. All suggestions are welcome.

这可能是一个单独的问题,但由于某种原因,这种搜索可能需要长达24秒的文件集10万。我曾尝试加入各种指标,但无济于事;在这方面的任何指针将是美妙的。

This is probably a separate question but for some reason this search can take up to 24 seconds on a document set of 100,000. I have tried adding various indexes but to no avail; any pointers in this regards would be fabulous.

这篇关于我怎样才能'和'多$ elemMatch条款与C#和MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆