mongodb将objectid添加到ID数组

发布于 2025-02-11 03:05:49 字数 1095 浏览 2 评论 0原文

我有诗歌模式,该模式在字段名称'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' } ],
}

enter image description here

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

勿忘初心 2025-02-18 03:05:49

您将键值对推入数组。

ObjectId: ('61f942b737bdc10018722539')

相反,应该是:

ObjectId('61f942b737bdc10018722539')
db.poems.updateOne(
  { title: "My stillness" },
  { $push: { communities: ObjectId('61f942b737bdc10018722539') } }
)

示例mongo playground

You are pushing key-value pair into the array.

ObjectId: ('61f942b737bdc10018722539')

Instead, it should be:

ObjectId('61f942b737bdc10018722539')
db.poems.updateOne(
  { title: "My stillness" },
  { $push: { communities: ObjectId('61f942b737bdc10018722539') } }
)

Sample Mongo Playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文