MongoDb,查找特定 objects,匹配特定值的嵌套值

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

我是 Mongo 的新手,我无法解决这个问题。其实我已经自己试了半天了:(

我想要的是找到 "ONLY" 某个用户插入的消息..

这是我的collection。

(如果看起来很乱,我会link改成图片) image as link

我想展示的是: 来自 "user" 的所有 "msg" 和 _id : ObjectId("57f383a6ace5ceb9af033511")

我希望有人能指导我,甚至告诉我这个 collection 是否不好或什么..

谢谢;)

关于这个话题还有一个问题:

How to select a single field in MongoDB?

在 find 方法中,您可以传递另一个对象(查询除外),告诉 return 哪些字段。

对你来说,它看起来像这样:

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

其中 1{messages:1} = select "messages" 字段中。

之前问过的类似问题

How to filter array in subdocument with MongoDB

关于你使用聚合函数的问题

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

结果:

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