【问题标题】:delete inside a document - mongoDB在文档中删除 - mongoDB
【发布时间】:2022-01-17 08:20:59
【问题描述】:

我正在使用 db.collection(collectionName) 获得一个特定的集合——它给我带来了 3 个对象(如图所示)。我想访问一个特定的对象(例如 screen-1)并根据它的 id 删除广告数组中的第一个元素。 我尝试按照以下方式进行操作,但它会提示 find(..).deleteMany(..) 不是函数。 有人可以帮忙吗?

dbo
      .collection(collectionName)
      .find({ screen: client.screen })
      .deleteMany({
        id: commid,
      })
      .then((result) => {
        if (result.deletedCount === 1) {
          console.log("Successfully deleted one document.");
        } else {
          console.log(
            "No documents matched the query. Deleted 0 documents."
          );
        }
      });

client.screen 包含 screen-1,commid 包含 1(我想删除 数组中的第一个元素,所以它的 id 是 1)

【问题讨论】:

  • 你不想删除那个对象,你想更新它。

标签: mongodb collections mongodb-query


【解决方案1】:

您需要更新文档并从数组中提取元素,因为您不想删除整个文档:

   db.collectionName.update({ screen:"screen-1" },{ $pull: { 'commercials.id': 1 }} );

【讨论】:

  • 非常感谢!!!!最终我所做的是 - db.collection(collectionName).updateMany( { screen: "screen-1" }, { $pull: { commeracials: { id: Commid } } } );
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 2013-09-14
  • 2016-04-20
相关资源
最近更新 更多