如何使用 $ne 操作符查询 MongoDB?
若要使用 $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 }
广告