Terkel Jungløw
Terkel Jungløw

Reputation: 55

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 ;)

Upvotes: 0

Views: 704

Answers (2)

Kumar
Kumar

Reputation: 907

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 "
    ]
}

Upvotes: 1

ToreDenStore
ToreDenStore

Reputation: 46

There is another question regarding this topic:

How to select a single field in MongoDB?

In the find method you can pass another object (except for the query) that tells what field(s) to return.

For you it would looks something like this:

db.student.find({"_id" : ObjectId("57f50608ace5ceb9af033528")}, {messages:1})

where 1 in {messages:1} = select the "messages" field.

Upvotes: 0

Related Questions