gpt4 book ai didi

内部数组的 Mongodb count()

转载 作者:可可西里 更新时间:2023-11-01 09:12:23 25 4
gpt4 key购买 nike

我有以下 MongoDB 集合 db.students:

/* 0 */
{
"id" : "0000",
"name" : "John"
"subjects" : [
{
"professor" : "Smith",
"day" : "Monday"
},
{
"professor" : "Smith",
"day" : "Tuesday"
}
]
}

/* 1 */
{
"id" : "0001",
"name" : "Mike"
"subjects" : [
{
"professor" : "Smith",
"day" : "Monday"
}
]
}

我想查找给定学生的科目数。我有一个问题:

 db.students.find({'id':'0000'})

这将返回学生文档。我如何找到“主题”的计数?它在一个简单的查询中是否可行?

最佳答案

如果查询只返回一个元素:

db.students.find({'id':'0000'})[0].subjects.length;

对于游标中的多个元素:

db.students.find({'id':'0000'}).forEach(function(doc) {
print(doc.subjects.length);
})

不要忘记在查询中或检查 .length 之前检查主题是否存在

关于内部数组的 Mongodb count(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27015981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com