【问题标题】:How to find an element in nested child array document in MongoDB using c#如何使用 C# 在 MongoDB 的嵌套子数组文档中查找元素
【发布时间】:2019-01-03 04:52:27
【问题描述】:

我有以下文档,我正在尝试搜索嵌套文档“ids”中的元素,

如果找到元素返回值 bool 或 count。我尝试使用 Mongodb 查询,但不确定如何为数组元素编写查询。 错误:-Operator == cannot be applied to operands of type 'string[]' and 'string'

foreach (var req in _addUpdateRailsObjectInfoRequest.ids)
{
      string value=req.id

  var isIdExists = Builders<RailsData>.Filter.And(
  Builders<RailsData>.Filter.ElemMatch(c => c.content.queryInclude, c => c.type == req.type),
  Builders<RailsData>.Filter.ElemMatch(c => c.content.queryInclude, c => c.ids == value));
 }

//c.id==value 附近的最后一行出错。运算符 == 不能应用于 'string[]' 和 'string' 类型的操作数

 {
        "_id" : ObjectId("5c2d3e700aff6771ebfc88ea"),
        "name" : "Toyota",
            "content" : {
            "queryInclude" : [ 
                {
                    "type" : "departments",
                    "ids" : [ 
                        "21", 
                        "18", 
                        "19", 
                        "29", 
                        "30"
                    ]
                }
            ]
        }
    }

//

public class RailsData
{
    public string name { get; set; }
    public content content { get; set; }
}

 public class content
 {
   public List<queryInclude> queryInclude { get; set; }
 }

    public class queryInclude
    {
        public string type { get; set; } 
        public string[] ids { get; set; }
    }

【问题讨论】:

  • 这个怎么样:Builders&lt;RailsData&gt;.Filter.ElemMatch(c =&gt; c.content.queryInclude, c =&gt; c.ids.Contains(value));?

标签: c# mongodb linq mongodb-query


【解决方案1】:

异常消息是不言自明的:您不能在字符串和string[] 数组之间使用相等比较运算符 (==),因为它们具有不同的类型。根据ElemMatch documentation,可以使用Any()扩展方法:

Builders<RailsData>.Filter.ElemMatch(c => c.content.queryInclude, c => c.ids.Any(x => x == value));

或者使用Contains() 作为替代:

Builders<RailsData>.Filter.ElemMatch(c => c.content.queryInclude, c => c.ids.Contains(value));

【讨论】:

  • 感谢您的回复,使用 Contains 后没有错误。但是如果找到元素如何返回值呢?
猜你喜欢
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 2019-09-24
  • 2022-06-11
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
相关资源
最近更新 更多