我正在使用mongoDB与nodejs服务器合作。现在我有一个示例数据:
{
"_id": ObjectId("555f1c0c7f4b820758b439b0"),
"user": "Guest1",
"friend": [{
"myfriend": "Guest2",
"info": []
}, {
"myfriend": "Guest3",
"info": []
}]
}
现在我想把所有"我的朋友"进入数组,像这样:
var listfriend = ["Guest2","Guest3"];
那我该怎么办呢?
感谢阅读:)
答案 0 :(得分:2)
尝试使用 map()
方法,如下所示:
var listfriend = db.names.findOne(
{"user" : "Guest1"},
{"_id": 0, "friend": 1}
).friend.map(function(obj){
return obj.myfriend;
});
console.log(listfriend); // ["Guest2","Guest3"]
答案 1 :(得分:0)
您想使用聚合框架吗?
var aggregateFriends = function( db, callback)
{
db.collection('test').aggregate(
[
{ $unwind: "$friend" },
{ $group: { _id: "$user", friends: {$push: "$friend.myfriend" } } }
]
).toArray( function( err, result ) {
console.log(result);
db.close();
} );
};
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
aggregateFriends( db, function() { db.close(); });
} );