首页 > 解决方案 > 如何使用 C# 过滤 MongoDB 数组以仅返回我需要的特定记录

问题描述

我的查询。

public List<T> GetETrannsfer<T>(string table, string Branch, string userName, string status)
        {
            var collection = db.GetCollection<T>(table);
            var filter = Builders<T>.Filter.And(Builders<T>.Filter.Regex("Branch", new BsonRegularExpression("/^" + Branch + "$/i")),
                Builders<T>.Filter.Eq("eLogInfo.userName", userName),
                Builders<T>.Filter.Eq("eLogInfo.status", status));
            return collection.Find(filter).ToList();
        }

我的设备LogModel

[BsonIgnoreExtraElements]
    public class EquipmentLogModel
    {

        [BsonId]
        public ObjectId _id { get; set; }
        public string eLogType { get; set; }
        public string Branch { get; set; }
        public EquipmentLogInfoModel[] eLogInfo { get; set; }

    }
[BsonIgnoreExtraElements]
    public class EquipmentLogInfoModel
    {
        [BsonId]
        public ObjectId _id { get; set; }
        public string userName { get; set; }
        public string eModel { get; set; }
        public string comments { get; set; }
        public string eDescription { get; set; }
        public string serialNum { get; set; }
        public string status { get; set; }
    }

如果数组中的一个对象包含过滤后的变量,MongoDB 会向我发送数组中所有对象的结果。我只需要包含特定变量的对象。

所以我尝试按照建议使用 ElemMatch 我仍然得到相同的结果记录没有被过滤结果包含特定数组下的所有记录。

public EquipmentLogModel GetETrannsfer(string table, string Branch, string userName, string status)
        {
            var collection = db.GetCollection<EquipmentLogModel>(table);
            var filter = Builders<EquipmentLogModel>.Filter.And(Builders<EquipmentLogModel>.Filter.Regex("Branch", new BsonRegularExpression("/^" + Branch + "$/i")),
               Builders<EquipmentLogModel>.Filter.ElemMatch(x => x.eLogInfo, x => x.status == status),
               Builders<EquipmentLogModel>.Filter.ElemMatch(x => x.eLogInfo, x => x.userName == userName));
            return collection.Find(filter).First();

        }

我也尝试了以下方法,它只返回了一条我需要不止一条的记录,并且我无法通过多个变量过滤返回。

 public EquipmentLogInfoModel GetETrannsfer(string table, string Branch, string userName, string status)
        {
            var filter = Builders<EquipmentLogModel>.Filter.And(Builders<EquipmentLogModel>.Filter.Regex("Branch", new BsonRegularExpression("/^" + Branch + "$/i")),
               Builders<EquipmentLogModel>.Filter.ElemMatch(x => x.eLogInfo, x => x.status == status),
               Builders<EquipmentLogModel>.Filter.ElemMatch(x => x.eLogInfo, x => x.userName == userName));

            var collection = db.GetCollection<EquipmentLogModel>(table).Find(filter)
               .FirstOrDefault();

            return collection.eLogInfo.FirstOrDefault(a => a.userName == userName);
        }

标签: c#arraysmongodb

解决方案


推荐阅读