您如何找到两级深度的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 } }热门推荐
10 古风婚礼祝福语唯美简短
11 开业经典祝福语简短
12 哥哥祝福语简短霸气句子
13 2026新年祝福语简短语
14 简短有内涵的祝福语
15 幼儿住院祝福语老师简短
16 小清新的祝福语简短
17 儿子31岁祝福语简短
18 团体年会祝福语简短霸气