首页 > 解决方案 > 推送嵌套数组中的元素( Mongodb )

问题描述

我命名的 Mongodb 数据库集合msgs如下所示:

[
   { 
     "_id" : ObjectId("5b45c387d774550874df7d47"),
     "userID" : "olivia",
     "friends" : [ 
                   { "userID" : "tom", "messages" : [ ] },
                   { "userID" : "sophia", "messages" : [ ] },
                   { "userID" : "katrina", "messages" : [ ] }  
                 ] 
   }
   { 
     "_id" : ObjectId("5b45c39fd774550874df7d4a"),
     "userID" : "tom",
     "friends" : [ 
                   { "userID" : "steve", "messages" : [ ] },
                   { "userID" : "olivia", "messages" : [ ] } 
                 ] 
   }
]

我想通过在"messages"数组中推送消息来更新这个集合。

在前端,用户可能会向用户olivia发送一条消息(以字符串格式)tom。所以我想写一个语句,将消息(任何字符串)推送到 olivia 用户的消息数组中。

例如:

如果向olivia发送消息。我想要新的数据库如下:"Hey Tom!"tom

[
   { 
     "_id" : ObjectId("5b45c387d774550874df7d47"),
     "userID" : "olivia",
     "friends" : [ 
                   { "userID" : "tom", "messages" : [ { "text" : "Hey Tom!" } ] },
                   { "userID" : "sophia", "messages" : [ ] },
                   { "userID" : "katrina", "messages" : [ ] }  
                 ] 
   }
   { 
     "_id" : ObjectId("5b45c39fd774550874df7d4a"),
     "userID" : "tom",
     "friends" : [ 
                   { "userID" : "steve", "messages" : [ ] },
                   { "userID" : "olivia", "messages" : [ ] } 
                 ] 
   }
]

我试过这个说法,但没有奏效:

db.msgs.update({"userID":"olivia","friends.userID":"tom"},{$push:{"messages":{text:"Hey Tom!"}}})

标签: arraysmongodbmultidimensional-array

解决方案


读取 $elemMatch 标记和“$”位置运算符以访问数组内的字段。

这是您的查询。

db.msgs.update({"userID":"olivia","friends":{$elemMatch:{"userID":"tom"}}},{$push:{"friends.$.messages":{text:"hello"}}})

推荐阅读