使用C#查询MongoDB嵌套数组文档

时间:2016-02-23 10:25:54

标签: c# arrays json mongodb mongodb-.net-driver

我正在尝试使用C#在MongoDB中使用嵌套数组文档实现文本搜索功能。我有一个以下格式的MongoDB集合。

{    
   "_id" : ObjectId("56c6f03ffd07dc1de805e84f"),
   "Customers" : {
            "Contact" : [ 
                           [
                             { 
                                "FirstName" : "Swetha", 
                                "LastName" : "DevAnand"
                             }
                           ]
                        ]
                   }
}

Mongo查询:

  db.test_collection.find({"Customers.Contact":{$elemMatch:{$elemMatch:{LastName: /.*Dev.*/}}}});

与上面的MongoDB查询一样,我想使用C#对BSON文档的最内层数组进行LIKE搜索。但是,我在Mongo Query中使用嵌套的$ elemMatch实现了这一点。但是在尝试在C#中执行相同操作时,它需要每个ElemMatch Query的字段名。在上述情况下,Contact字段的最内层数组没有任何显式字段名称。到目前为止,我已经尝试了以下所有C#代码来实现该方案,但它们都没有帮助。

var regex = new BsonRegularExpression(searchVal,"i");

query = Query.And(Query.ElemMatch("Customers.Contact", Query.And(Query.ElemMatch("LastName", Query.Matches("LastName", regex)))));
query = Query.And(Query.Matches("Customers.Contact.$.LastName",regex));
query = Query.And(Query.ElemMatch("Customers.Contact.$", Query.EQ("LastName", regex)));                 
query = Query.And(Query.ElemMatch("Customers.Contact.$", Query.Matches("LastName", regex)));
query = Query.And(Query.ElemMatch("Customers.Contact", Query.And(Query.ElemMatch("$", Query.EQ("LastName", regex)))));

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

经过一周的奋斗,找到了办法。实现上述MongoDB查询的最佳方法是将其反序列化为BsonDocument,然后将其作为过滤器传递给FindAsync。

var bQuery = "{'Customers.Contact':{$elemMatch:{$elemMatch:{LastName: /.*Dev.*/}}}}";
var filter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(bQuery);
var result = collection.FindSync(filter).ToList();

感谢Mr.Saleem。有关详细信息,请参阅以下链接。 How to implement MongoDB nested $elemMatch Query in C#

答案 1 :(得分:0)

我不了解您的背景 - 所以请尽量帮助您。 请注意,联系人是列表而不是数组 这将有助于您构建自己的过滤器表达式

namespace ClassLibrary1
{
    using System;
    using System.Collections.Generic;
    using System.Linq.Expressions;

    using MongoDB.Driver;

    /// <summary>
    /// The class 1.
    /// </summary>
    public class Class1
    {
        /// <summary>
        /// The get data.
        /// </summary>
        public async void GetData()
        {
            var context = new Context();
            var searchString = "1234";
            Expression<Func<SomeThing, bool>> filter = x =>
            x.Contact.Exists(s => s.FirstName == searchString
            && x.Contact.Exists(l=>l.LastName == searchString));
            var result = await context.SomeThingCollection.FindAsync(filter);
        }
    }

    /// <summary>
    /// The context.
    /// </summary>
    public class Context
    {
        public const string CONNECTION_STRING_NAME = " ";
        public const string DATABASE_NAME = " ";
        public const string COLLECTION_NAME = "name";
        private static readonly IMongoClient _client;
        private static readonly IMongoDatabase _database;
        static Context()
        {
            var connectionString = "connectionString";
            _client = new MongoClient(connectionString);
            _database = _client.GetDatabase(DATABASE_NAME);
        }
        public IMongoCollection<SomeThing> SomeThingCollection
        {
            get
            {
                return _database.GetCollection<SomeThing>(COLLECTION_NAME);
            }
        }
    }

    public class SomeThing
    {
        public List<Contact> Contact { get; set; }
    }

    public class Contact
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}