arrays - 推送嵌套数组中的元素( 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!"}}})
解决方案
读取 $elemMatch 标记和“$”位置运算符以访问数组内的字段。
这是您的查询。
db.msgs.update({"userID":"olivia","friends":{$elemMatch:{"userID":"tom"}}},{$push:{"friends.$.messages":{text:"hello"}}})
推荐阅读
- reactjs - 如何在 reducer 函数中将值推送到数组(React js、Typescript、Redux)
- python - 为什么我在 tensorboard t-sne RANDOM 中对 cnn 图像特征的可视化?
- flutter - 如何在 Flutter 中处理/杀死 PageView 中的页面
- javascript - 如何使用 vue-slick 包实现自己的操作按钮
- entity-framework - EF LINQ通过另一个列表中不存在的值获取记录列表
- python-sphinx - Sphinx 标题中的重音字符
- node.js - 如何判断节点是如何安装的?
- swift - 有什么方法可以将 tradingview 图表导入我的 ios 应用程序?
- javascript - 用 craco 去掉 create-react-app 开发服务器
- statistics - 调整多重比较问题的值