2

I have below document, I am trying to search an element which is inside the nested document "ids",

If element is found return value bool or count. I tried with Mongodb query but not sure how to write a query for an array elements. error :-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));
 }

//Error at last line near c.id==value. Operator == cannot be applied to operands of type 'string[]' and '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; }
    }
1
  • 1
    How about this one: Builders<RailsData>.Filter.ElemMatch(c => c.content.queryInclude, c => c.ids.Contains(value));? Commented Jan 3, 2019 at 4:58

1 Answer 1

3

The exception message is self-explanatory: you cannot use equality comparison operator (==) between a string and string[] array, because they have different types. According to ElemMatch documentation, you can use Any() extension method:

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

Or use Contains() as alternative:

Builders<RailsData>.Filter.ElemMatch(c => c.content.queryInclude, c => c.ids.Contains(value));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply, There is no error after using Contains. But how to return a value if element is found?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.