MongoDB - 如何检查集合中的平等性和嵌入文档中的平等性?
为此,请使用 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" } }
广告