Home > Mobile >  Not equal to operator for MongoDB query in C#
Not equal to operator for MongoDB query in C#

Time:02-25

I have one query in MongoDB like below,

db.getCollection('Student')
.find({_id: 123, $where:"this.section != this.upperSection"})

How to convert this query to execute from C# code?

I tried using the below code but that didn't work. Can you guide me?

var builder = Builders<BsonDocument>.Filter;

var filter = builder.Not("section ", "upperSection");

Sample Mongo docs - & the expected outcome should be doc2

//doc1
{
    "_id" : "123",
    "section" : "X",
    "upperSection" : "X"
}

//doc2
{
    "_id" : "123",
    "section" : "X",
    "upperSection" : "Y"
}

CodePudding user response:

You can apply the query as BsonDocument.

FilterDefinition<BsonDocument> filter = new BsonDocument("$expr", 
    new BsonDocument("$ne",
        new BsonArray { "$section", "$upperSection" }
    )
);

Output

  • Related