MongoDB C# Query Array of Objects that contain a property value

前端 未结 1 1192
北海茫月
北海茫月 2021-01-20 14:03

My documents have an array property in them. Lets call it arrayProperty something like this:

 {
  _id: mongoObjectIdThingy,
  arrayProperty: [
    {string1:         


        
相关标签:
1条回答
  • 2021-01-20 14:44

    I believe you are looking for the In FilterDefinition, which would make your Builder look like this;

    return Builders<MyObject>.Filter.ElemMatch(
                o => o.arrayProperty,
                Builders<ArrayProperty>.Filter.In(y => y.string1, listToFind));
    

    This builds this query

    db.MyObject.find({ "arrayProperty" : { "$elemMatch" : { "string1" : { "$in" : ["a", "b", "aString"] } } } })
    

    To be able to use the Regex you would have to build a different query (I'm not on coffee so this is without any warranty)

            var listToFind = new List<string> { "a", "b", "astring" };
    
            var regexList = listToFind.Select(x => new BsonRegularExpression(x, "i"));
    
            var filterList = new List<FilterDefinition<MyObject>>();
            foreach (var bsonRegularExpression in regexList)
            {
                FilterDefinition<MyObject> fil = Builders<MyObject>.Filter.ElemMatch(o => o.arrayProperty, Builders<ArrayProperty>.Filter.Regex(
                     x => x.string1,
                     bsonRegularExpression));
    
                filterList.Add(fil);
            }
    
    
            var orFilter = Builders<MyObject>.Filter.Or(filterList);
    
            var result = collection.Find(orFilter).ToList();
    

    Which builds the follow query

    db.MyObject.find({ "$or" : [{ "arrayProperty" : { "$elemMatch" : { "string1" : /a/i } } }, { "arrayProperty" : { "$elemMatch" : { "string1" : /b/i } } }, { "arrayProperty" : { "$elemMatch" : { "string1" : /astring/i } } }] })
    
    0 讨论(0)
提交回复
热议问题