要比较两个字段,请在MongoDB中使用$where。首先让我们创建一个包含文档的集合-
> db.demo7.insertOne({"FirstName1":"JOHN","FirstName2":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5e0ccd1a25ddae1f53b6222f") } > db.demo7.insertOne({"FirstName1":"Carol","FirstName2":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e0ccd2725ddae1f53b62230") } > db.demo7.insertOne({"FirstName1":"bob","FirstName2":"BOB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e0ccd3225ddae1f53b62231") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.demo7.find();
这将产生以下输出-
{ "_id" : ObjectId("5e0ccd1a25ddae1f53b6222f"), "FirstName1" : "JOHN", "FirstName2" : "John" } { "_id" : ObjectId("5e0ccd2725ddae1f53b62230"), "FirstName1" : "Carol", "FirstName2" : "Mike" } { "_id" : ObjectId("5e0ccd3225ddae1f53b62231"), "FirstName1" : "bob", "FirstName2" : "BOB" }
这是在对两个字段之一执行操作时比较两个字段的查询-
> db.demo7.find({$where: "this.FirstName1.toLowerCase() == this.FirstName2.toLowerCase()"});
这将产生以下输出-
{ "_id" : ObjectId("5e0ccd1a25ddae1f53b6222f"), "FirstName1" : "JOHN", "FirstName2" : "John" } { "_id" : ObjectId("5e0ccd3225ddae1f53b62231"), "FirstName1" : "bob", "FirstName2" : "BOB" }