mongodb将objectid添加到ID数组
我有诗歌模式,该模式在字段名称'communities'下具有链接的objectid数组:
{
_id: ObjectId("61659ef70e87b90018f7baa1"),
schemaName: 'Poem',
helps: [ ObjectId("5d15c609832d390c41ab6872") ],
communities:
[ ObjectId("5eafbabaf0be6f0017303eb3"),
ObjectId("5eba549a45bd9300170f6311") ],
}
我正在尝试使用UpdateOne和$ push向数组中添加一个新的Objectid:
db.poems.updateOne(
{title: "My stillness"},
{$push: {communities: {ObjectId: ('61f942b737bdc10018722539')}}}
)
添加新ID时,它不是正确的格式(另请参见MongoDB指南针的附件图像,以进一步清楚格式的差异)。如何调整我的updateOne/$ push方法以正确格式添加objectID?谢谢
{
_id: ObjectId("61659ef70e87b90018f7baa1"),
schemaName: 'Poem',
helps: [ ObjectId("5d15c609832d390c41ab6872") ],
communities:
[ ObjectId("5eafbabaf0be6f0017303eb3"),
ObjectId("5eba549a45bd9300170f6311"),
{ ObjectId: '61f942b737bdc10018722539' } ],
}
I have Poems schema which has a linked array of ObjectIds under field name 'communities':
{
_id: ObjectId("61659ef70e87b90018f7baa1"),
schemaName: 'Poem',
helps: [ ObjectId("5d15c609832d390c41ab6872") ],
communities:
[ ObjectId("5eafbabaf0be6f0017303eb3"),
ObjectId("5eba549a45bd9300170f6311") ],
}
I am trying to add a new ObjectId to the array using updateOne and $push:
db.poems.updateOne(
{title: "My stillness"},
{$push: {communities: {ObjectId: ('61f942b737bdc10018722539')}}}
)
While the new Id gets added, it is not in the correct format (see also attached image from MongoDB Compass for further clarity on the difference in format). How can I adjust my updateOne/$push method to add the ObjectId in the correct format? Thanks
{
_id: ObjectId("61659ef70e87b90018f7baa1"),
schemaName: 'Poem',
helps: [ ObjectId("5d15c609832d390c41ab6872") ],
communities:
[ ObjectId("5eafbabaf0be6f0017303eb3"),
ObjectId("5eba549a45bd9300170f6311"),
{ ObjectId: '61f942b737bdc10018722539' } ],
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将键值对推入数组。
相反,应该是:
示例mongo playground
You are pushing key-value pair into the array.
Instead, it should be:
Sample Mongo Playground