Javascript 如何访问MongoDB查询中的子文档?
所以我有下面的代码。我需要它在MongoDB shell中运行。它在数据库中查询属性标记为true的人员。现在我遇到了麻烦,因为我不知道如何将查询的numcollect部分更改为数组。我正在尝试平均numcollect集合中的所有数字。我知道这个代码是不正确的,但它显示了我正在尝试做什么。我需要改变什么 数据库:Javascript 如何访问MongoDB查询中的子文档?,javascript,json,mongodb,cursor,bson,Javascript,Json,Mongodb,Cursor,Bson,所以我有下面的代码。我需要它在MongoDB shell中运行。它在数据库中查询属性标记为true的人员。现在我遇到了麻烦,因为我不知道如何将查询的numcollect部分更改为数组。我正在尝试平均numcollect集合中的所有数字。我知道这个代码是不正确的,但它显示了我正在尝试做什么。我需要改变什么 数据库: { "name":"John Doe", "attribute":"true", "numcollect":{ "one":12,
{
"name":"John Doe",
"attribute":"true",
"numcollect":{
"one":12,
"two":22,
"three":44,
"four":79
}
},
{
"name":"Jane Doe",
"attribute":"true",
"numcollect":{
"one":13,
"two":55,
"three":18
}
}
代码
var-people=[];
var指数=0;
db.test.find({“attribute”:“true”}).forEach(
函数(myDoc){
var person=新对象();
person.name=myDoc.name;
person.numcollect=myDoc.numcollect;
person.numavg=0;
var i=0;
对于(i=0;i),首先,这个问题与MongoDB无关(因为它或多或少使用标准JavaScript实现)。您只想知道如何在JavaScript中循环字典/对象中的值:
for (var i in numcollect) {
if (numcollect.hasOwnProperty(i)) {
person.numavg += numcollect[i];
}
}
这可以是一个答案:
collection.mapReduce(function(){
for(var key in this.numcollect)
emit(this._id, this.numcollect[key])
}, function(key, values){
return Array.sum(values)
},{
out:{inline:1}
}, function(err, doc){
if(err){
console.log("mapReduce ERROR", err);
}else{
console.log("mapReduce Result", doc);
}
})
这与我所拥有的有什么不同?如果您使用foreach循环而不是标准for循环,我唯一看到的是。numcollect不是数组,而是子文档。我需要知道如何提取所有值。@bam2403没有foreach循环。这是不同的,因为您正在尝试检索numcollect[0],numcollecet[1],…
但是numcollect
没有这样的属性。对于(numcollect中的var i)
循环属性,基本上i
变成字符串“一”、“二”,…
。更不用说字典没有长度。)@bam2403 P.S.我确实看到numcollect
不是数组。请尝试代码,然后进行注释,好吗?
collection.mapReduce(function(){
for(var key in this.numcollect)
emit(this._id, this.numcollect[key])
}, function(key, values){
return Array.sum(values)
},{
out:{inline:1}
}, function(err, doc){
if(err){
console.log("mapReduce ERROR", err);
}else{
console.log("mapReduce Result", doc);
}
})