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

前端 未结 1 1194
北海茫月
北海茫月 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.Filter.ElemMatch(
                o => o.arrayProperty,
                Builders.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 { "a", "b", "astring" };
    
            var regexList = listToFind.Select(x => new BsonRegularExpression(x, "i"));
    
            var filterList = new List>();
            foreach (var bsonRegularExpression in regexList)
            {
                FilterDefinition fil = Builders.Filter.ElemMatch(o => o.arrayProperty, Builders.Filter.Regex(
                     x => x.string1,
                     bsonRegularExpression));
    
                filterList.Add(fil);
            }
    
    
            var orFilter = Builders.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)
提交回复
热议问题