Reputation: 91
i'm working with nodejs server using mongoDB. Now i have a sample data:
{
"_id": ObjectId("555f1c0c7f4b820758b439b0"),
"user": "Guest1",
"friend": [{
"myfriend": "Guest2",
"info": []
}, {
"myfriend": "Guest3",
"info": []
}]
}
Now i want to put all "myfriend" into array, like this:
var listfriend = ["Guest2","Guest3"];
So how can i do it ?
Thank for read :)
Upvotes: 1
Views: 123
Reputation: 103305
Try using the map()
method as follows:
var listfriend = db.names.findOne(
{"user" : "Guest1"},
{"_id": 0, "friend": 1}
).friend.map(function(obj){
return obj.myfriend;
});
console.log(listfriend); // ["Guest2","Guest3"]
Upvotes: 2
Reputation: 3012
Did you want to use the aggregation framework?
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(); });
} );
Upvotes: 0