要使用 $ne 运算符查询 MongoDB,以下是语法 -
db.yourCollectionName.find({yourFieldName:{$ne:yourValue}}).pretty();
让我们创建一个包含文档的集合 -
> db.notEqaulToDemo.insertOne({"StudentName":"Larry","StudentMathMarks":68}); { "acknowledged" : true, "insertedId" : ObjectId("5cbd3a6bde8cc557214c0ded") } > db.notEqaulToDemo.insertOne({"StudentName":"Chris","StudentMathMarks":88}); { "acknowledged" : true, "insertedId" : ObjectId("5cbd3a79de8cc557214c0dee") } > db.notEqaulToDemo.insertOne({"StudentName":"David","StudentMathMarks":45}); { "acknowledged" : true, "insertedId" : ObjectId("5cbd3a89de8cc557214c0def") } > db.notEqaulToDemo.insertOne({"StudentName":"Carol","StudentMathMarks":69}); { "acknowledged" : true, "insertedId" : ObjectId("5cbd3a97de8cc557214c0df0") }
借助find()方法显示集合中的所有文档-
> db.notEqaulToDemo.find().pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5cbd3a6bde8cc557214c0ded"), "StudentName" : "Larry", "StudentMathMarks" : 68 } { "_id" : ObjectId("5cbd3a79de8cc557214c0dee"), "StudentName" : "Chris", "StudentMathMarks" : 88 } { "_id" : ObjectId("5cbd3a89de8cc557214c0def"), "StudentName" : "David", "StudentMathMarks" : 45 } { "_id" : ObjectId("5cbd3a97de8cc557214c0df0"), "StudentName" : "Carol", "StudentMathMarks" : 69 }
以下是对 MongoDB $ne 运算符的查询 -
> db.notEqaulToDemo.find({StudentMathMarks:{$ne:88}}).pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5cbd3a6bde8cc557214c0ded"), "StudentName" : "Larry", "StudentMathMarks" : 68 } { "_id" : ObjectId("5cbd3a89de8cc557214c0def"), "StudentName" : "David", "StudentMathMarks" : 45 } { "_id" : ObjectId("5cbd3a97de8cc557214c0df0"), "StudentName" : "Carol", "StudentMathMarks" : 69 }