使用mongodb 3.0 - 如果我有这样的文档(简单版本):
{
"_id": "10",
"Timestamp": ISODate("2015-09-07T09:54:45.000Z"),
"StudentData": [
{
"Name": "John"
"Town": "ZZZZZ"
"Available": true
},
{
"Name": "Mary"
"Town": "XXXXXX"
"Available": false
}
]
}
我需要像这样打印的结果:
Mon Sep 07 2015 10:54:45 GMT+0100 (GMT Daylight Time),John,true
Mon Sep 07 2015 10:54:45 GMT+0100 (GMT Daylight Time),Mary,false
我试过这个:
db.students.find(
{_id:10})
.forEach(function(x){
print(
x.Timestamp
+","+
x.StudentData.Name
+","+
x.StudentData.Available
);
});
但我得到的结果是
2015年9月7日星期一10:54:45 GMT + 0100(GMT日光时间),未定义,未定义
也许这是正确的轨道:
var cursor =
db.students.aggregate(
{$match: {_id: "10"}},
{$unwind: '$StudentData'});
print(cursor.result);
还是我的标志?
答案 0 :(得分:2)
由于 $unwind
将" split"每个数组元素输出一个文档的数组,因此管道结果将具有您可以打印的两个文档。由于 aggregate()
方法返回cursor,您需要迭代光标以访问文档并使用 forEach()
方法。请考虑以下调整:
var printStudentData = function (doc) {
print(doc.Timestamp +", " + doc.StudentData.Name + ", " + doc.StudentData.Available);
}
var cur = db.students.aggregate([
{$match: {_id: "10"}},
{$unwind: '$StudentData'}
]);
cur.forEach(printStudentData);
<强>输出强>
Mon Sep 07 2015 10:54:45 GMT+0100 (GMT Daylight Time), John, true
Mon Sep 07 2015 10:54:45 GMT+0100 (GMT Daylight Time), Mary, false
如果您想坚持使用 find()
光标,那么当您在 {{3}时,您需要遍历StudentData
数组} 游标循环,类似于:
var printStudentData = function (doc) {
print(doc.Timestamp +", " + doc.StudentData.Name + ", " + doc.StudentData.Available);
};
var result = db.students.find({_id: "10"});
result.forEach(function (x){
x.StudentData.forEach(function (data){
var obj = {
"StudentData": {}
};
obj["Timestamp"] = x.Timestamp;
obj["StudentData"]["Name"] = data.Name;
obj["StudentData"]["Available"] = data.Available;
printStudentData(obj);
});
});