为此,请在MongoDB中使用$where检查。让我们创建一个包含文档的集合-
> db.demo292.insertOne({FirstName:"Chris",LastName:"Brown", ... "Friend":{FirstName:"David","LastName":"Miller"} ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e4c10aa5d93261e4bc9ea30") } > db.demo292.insertOne({FirstName:"John",LastName:"Doe", ... "Friend":{FirstName:"Mike","LastName":"Doe"} ...} ...); { "acknowledged" : true, "insertedId" : ObjectId("5e4c10dc5d93261e4bc9ea31") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo292.find();
这将产生以下输出-
{ "_id" : ObjectId("5e4c10aa5d93261e4bc9ea30"), "FirstName" : "Chris", "LastName" : "Brown", "Friend" : { "FirstName" : "David", "LastName" : "Miller" } } { "_id" : ObjectId("5e4c10dc5d93261e4bc9ea31"), "FirstName" : "John", "LastName" : "Doe", "Friend" : { "FirstName" : "Mike", "LastName" : "Doe" } }
以下是检查集合和嵌入式文档中是否相等的查询-
> db.demo292.find({$where: 'this.Friend.LastName === this.LastName'})
这将产生以下输出-
{ "_id" : ObjectId("5e4c10dc5d93261e4bc9ea31"), "FirstName" : "John", "LastName" : "Doe", "Friend" : { "FirstName" : "Mike", "LastName" : "Doe" } }