Terkel Jungløw Terkel Jungløw - 2 months ago 13
Node.js Question

MongoDb, find specific objects, nested values matching specific value



db.Rooms.find({"name" : "room3"}).pretty()
{
"_id" : ObjectId("57f50608ace5ceb9af033528"),
"name" : "room3",
"userData" : {
"user" : ObjectId("57f4d142ace5ceb9af033521"),
"date" : "Wed Oct 05 2016 15:54:16 GMT+0200"
},
"active" : true,
"users" : [
{
"uid" : ObjectId("57f383a6ace5ceb9af033511")
},
{
"uid" : ObjectId("57f4d142ace5ceb9af033521")
}
],
"messages" : [
{
"msg" : "first test since statement ",
"time" : "Wed Oct 05 2016 15:55:26 GMT+0200",
"user" : ObjectId("57f383a6ace5ceb9af033511")
},
{
"msg" : "second test since statement ",
"time" : "Wed Oct 05 2016 15:57:35 GMT+0200",
"user" : ObjectId("57f4d142ace5ceb9af033521")
},
{
"msg" : "third test since statement ",
"time" : "Wed Oct 05 2016 15:58:11 GMT+0200",
"user" : ObjectId("57f383a6ace5ceb9af033511")
}
]
}





i am quite new to Mongo, and i am having trouble solving this. actually i have tried on my own for half a day allready :(

What i want, is to find "ONLY" the messages, that a certain user has inserted..

This is my collection.

(if it looks messy, i will link to an image instead)
image as link

What i want is to show:
all the "msg" from the "user" with _id : ObjectId("57f383a6ace5ceb9af033511")

i hope that someone can guide me or even tell me if this collection is bad or anything..

thx ;)

Answer

Similar Question asked before

How to filter array in subdocument with MongoDB

For you question using aggregate function

db.Room.aggregate(
    { $unwind: '$messages'},
    { $match: {'messages.user': {$eq: ObjectId("57f383a6ace5ceb9af033511")}}},
    { $group: {_id: '$_id', list: {$push: '$messages.msg'}}}

Result :

{
    "_id" : ObjectId("57f50608ace5ceb9af033528"),
    "list" : [ 
        "first test since statement ", 
        "third test since statement "
    ]
}