使用同一文档中的字段进行 MongoDB 查询?
你可以为此使用 $where 运算符。为了理解这个概念,让我们创建一个带有文件的集合。创建带有文件的集合的查询如下所示 −
> db.queryInSameDocumentsDemo.insertOne({"StudentDetails":{"StudentName":"John"},"NewStudentDetails":{"StudentName":"Carol"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90096ed3c9d04998abf017")
}
> db.queryInSameDocumentsDemo.insertOne({"StudentDetails":{"StudentName":"Bob"},"NewStudentDetails":{"StudentName":"Bob"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c900a435705caea966c5573")
}在集合中显示所有文件,借助 find() 方法。查询如下所示 −
> db.queryInSameDocumentsDemo.find().pretty();
输出如下 −
{
"_id" : ObjectId("5c90096ed3c9d04998abf017"),
"StudentDetails" : {
"StudentName" : "John"
},
"NewStudentDetails" : {
"StudentName" : "Carol"
}
}
{
"_id" : ObjectId("5c900a435705caea966c5573"),
"StudentDetails" : {
"StudentName" : "Bob"
},
"NewStudentDetails" : {
"StudentName" : "Bob"
}
}案例 1 − 以下是同一文档中带字段的查询。我们在这里使用了相等 (==) 运算符。查询如下所示 −
> db.queryInSameDocumentsDemo.find( { $where: "this.StudentDetails.StudentName == this.NewStudentDetails.StudentName" } ).pretty();输出如下 −
{
"_id" : ObjectId("5c900a435705caea966c5573"),
"StudentDetails" : {
"StudentName" : "Bob"
},
"NewStudentDetails" : {
"StudentName" : "Bob"
}
}案例 2 − 以下是同一文档中带字段的查询。我们使用了不等于运算符。
查询如下所示 −
> db.queryInSameDocumentsDemo.find( { $where: "this.StudentDetails.StudentName != this.NewStudentDetails.StudentName" } ).pretty();输出如下 −
{
"_id" : ObjectId("5c90096ed3c9d04998abf017"),
"StudentDetails" : {
"StudentName" : "John"
},
"NewStudentDetails" : {
"StudentName" : "Carol"
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP