0

I have some data that looks like this:

{
"_id" : "5227aa5d9881d31cd3aa0e78",
"Message" : "This is a message 5:47 PM",
"IssuedAt" : ISODate("2013-09-04T21:47:09.932Z"),
"Users" : [
    {
        "_id" : "dhBHuZL9M+hqtKIx14iu",
        "IsRead" : true
    },
    {
        "_id" : "SOMSOMOMODJFJDFKJKDJF",
        "IsRead" : false
    }
]
}

and I was hoping retrieve the following about one user:

{
  "_id" : "5227aa5d9881d31cd3aa0e78",
  "Message" : "This is a message 5:47 PM",
  "IssuedAt" : ISODate("2013-09-04T21:47:09.932Z"),
  "IsRead" : false
}

I tried this but it will only return the record with the whole subdocument:

db.collection.find({"Users": {$elemMatch: {"_id": 'dhBHuZL9M+hqtKIx14iu'}}}, {"Message": 1, "Users.$.IsRead": 1}).pretty()

Is there a way to get what I am looking for without using aggregate?

4

1 回答 1

0

在目前的要求中,我认为你必须重新设计你的架构。Schema 必须对您的查询更有效。可能是当前要求的架构将拥有用户集合

                 { 
                  "_id": "dhBHuZL9M+hqtKIx14iu" ,
                   "Name" : "Test",
                    "ReadMessages" [{}],
                    "UnReadMessage" [{}]
                 }

现在,对于任何用户,您都可以很容易地获得已读消息和未读消息。您必须触发一个更新语句才能将消息从未读移动到已读。但它会发生一次,休息阅读会非常快。我知道它不会解决您的问题,但可能会帮助您希望更改架构。

于 2013-09-05T06:24:53.000 回答