首页 > 解决方案 > 添加到数组 - 没有重复字段值的子文档

问题描述

我正在尝试将对象添加到 MongoDB 中的数组中。我不希望它被复制。

我正在尝试使用$addTosetin更新用户读取数组findOneAndUpdate。但是,由于时间戳,它正在插入重复;时间戳是一个重要的属性。我不能否定它。我可以根据键插入userId吗?请告诉我。

{
    _id: 'ddeecd8b-79b5-437d-9026-d0663b53ad8d',
     message: 'hello world notification',
     deliverToUsersList: [ '123-xxx-xx', '124-xxx-xx']
    userRead: [
     {
       isOpened: true,
       userId: '123-xxx-xx'
       updatedOn: new Date(Date.now()).toISOString()
     },
     {
       isOpened: true,
       userId: '124-xxx-xx'
       updatedOn: new Date(Date.now()).toISOString()
     }
    ]
}

标签: javascriptmongodb

解决方案


要将没有重复信息的新对象添加到userRead数组中,您必须在更新方法的查询过滤器中检查重复信息。例如,以下代码将不允许添加具有重复userId字段值的新对象。

new_userId = "999-xxx-xx"
new_doc = { userId: new_userId, isOpened: true, updatedOn: ISODate() }

db.test_coll.findOneAndUpdate(
   { _id: 'ddeecd8b-79b5-437d-9026-d0663b53ad8d', "userRead.userId": { $ne: new_userId } },
   { $push: { "userRead" : new_doc } },
)

推荐阅读