如何查找两层深的 MongoDB 记录?
要查找两层深的 MongoDB 记录,请在 MongoDB $where 内进行循环。让我们创建一个包含文档的集合 −
> db.demo468.insertOne(
... {
... "_id" : new ObjectId(),
... "FirstPosition" : {
... "StudentName" : "Chris",
... "StudentAge" : 23
... },
... "SecondPosition" : {
... "StudentName" : "David",
... "StudentAge" : 20
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e804e2fb0f3fa88e2279069")
}
> db.demo468.insertOne(
... {
... "_id" : new ObjectId(),
... "FirstPosition" : {
... "StudentName" : "Carol",
... "StudentAge" : 21
... },
... "SecondPosition" : {
... "StudentName" : "John",
... "StudentAge" : 22
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e804fb0b0f3fa88e227906a")
}在集合中使用 find() 方法显示所有文档 −
> db.demo468.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e804e2fb0f3fa88e2279069"), "FirstPosition" : { "StudentName" : "Chris",
"StudentAge" : 23 }, "SecondPosition" : { "StudentName" : "David", "StudentAge" : 20 } }
{ "_id" : ObjectId("5e804fb0b0f3fa88e227906a"), "FirstPosition" : { "StudentName" : "Carol",
"StudentAge" : 21 }, "SecondPosition" : { "StudentName" : "John", "StudentAge" : 22 } }以下是对 MongoDB 中两级深记录进行查询 −
> db.demo468.find({
... $where: function() {
... for (var i in this) {
... if (this[i]["StudentName"] == "John") {
... return true;
... }
... }
... return false;
... }
... })这将产生以下输出 −
{ "_id" : ObjectId("5e804fb0b0f3fa88e227906a"), "FirstPosition" : { "StudentName" : "Carol",
"StudentAge" : 21 }, "SecondPosition" : { "StudentName" : "John", "StudentAge" : 22 } }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP