MongoDB在$ pull条件之前填充项目

时间:2018-07-02 18:03:54

标签: mongodb mongoose

用户集合:

[
  {
    _id: '5b3935c2d4850aa2d9f0ae25',
    feedBucket: ['5b37d16665c4127e7a088812', '5b3a19c5be4949b0d74476d4']
  },
{
    _id: '35c2d4850aa2d9f0ae25ab39',
    feedBucket: ['5b37d16665c4127e7a088812', '5b3a19c5be4949b0d74476d4']
  }
]

帖子集:

[
  {
    _id: '5b37d16665c4127e7a088812',
    createdAt: 2018-07-01 23:12:50.232
  },
  {
    _id: '5b3a19c5be4949b0d74476d4',
    createdAt: 2018-05-01 23:12:50.232
  },
]

我要执行以下操作:

const date = new Date()
date.setMonth(date.getMonth() - 1)

await User.updateMany(
  {},
  { $pull: { feedBucket: { createdAt: { $lte: date } } } }
)

是否有任何方法可以在$ pull条件之前填充feedBucket项目? 还是feedBucket不应该是项目ID的数组,而是应该是项目文档的数组?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下代码:

createdAt

另一种选择是将feedBicket存储在{ _id: ObjectId, createdAt: Date } 中,例如

await User.updateMany(
  {},
  { $pull: { feedBucket: { createdAt: { $lte: date } } } }
)

然后您可以使用

进行查询
{
  "id": "cfafbeb1-8037-4d0c-896e-a46fb27ff229",
  "name": "SalesMarketing",
  "addRowsAPIEnabled": false,
  "configuredBy": "john@contoso.com",
  "isRefreshable": true,
  "isEffectiveIdentityRequired": true,
  "isEffectiveIdentityRolesRequired": true,
  "isOnPremGatewayRequired": false
}