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

时间:2016-10-05 14:16:28

标签: node.js mongodb nested-queries

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很新,我在解决这个问题上遇到了麻烦。实际上我已经半天尝试了自己:(

我想要的是找到“仅”某个用户插入的消息..

这是我的收藏。

(如果它看起来很乱,我会链接到图像) image as link

我想要的是显示: 来自“user”的所有“msg”_id:ObjectId(“57f383a6ace5ceb9af033511”)

我希望有人可以指导我,甚至告诉我这个收藏品是不是很糟糕......

thx;)

2 个答案:

答案 0 :(得分:1)

之前提出的类似问题

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

答案 1 :(得分:0)

关于这个主题还有另一个问题:

How to select a single field in MongoDB?

在find方法中,您可以传递另一个对象(查询除外),该对象指示要返回的字段。

对你而言,它看起来像这样:

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

1中的{messages:1} =选择"消息"字段。