我有一个包含以下文档的 Listing
集合:
{
owner: ObjectId('12345678'),
bids: [
{
amount: 36,
date: 2021-06-23T21:00:00.000+00:00,
placedBy: ObjectId('1111111')
},
{
amount: 16,
date: 2021-06-23T21:00:00.000+00:00,
placedBy: ObjectId('22223332')
}
]
}
我需要查询 bids
数组,但只有在满足 条件时才删除字段 placedBy
(对于数组中的所有元素)。这是我到目前为止:
async getBids(listingId: string, user: UserDocument) {
return this.listingModel.aggregate([
{ $match: { _id: Types.ObjectId(listingId) } },
{
$project: {
'bids.date': 1,
'bids.amount': 1,
'bids.placedBy': {
$cond: {
if: {
'$eq': ['$owner', Types.ObjectId(user.id)]
},
then: '$bids.placedBy',
else: '$$REMOVE'
}
}
}
}
])
}
这适用于条件为 false
( bids.placedBy
已删除)的情况,但是当条件满足时,我得到了这个( bids.placedBy
变成了所有 placedBy
的数组):bids: [
{
amount: 36,
date: 2021-06-23T21:00:00.000+00:00,
placedBy: [
ObjectId('1111111'),
ObjectId('22223332')
]
},
{
amount: 16,
date: 2021-06-23T21:00:00.000+00:00,
placedBy: [
ObjectId('1111111'),
ObjectId('22223332')
]
}
]
我怎样才能解决这个问题?
最佳答案
您可以使用 $map
遍历数组并设置条件
db.collection.aggregate([
{
$project: {
"bids": {
"$map": {
"input": "$bids",
"in": {
amount: "$$this.amount",
date: "$$this.date",
placedBy: {
$cond: [ { "$eq": [ "$owner", 1 ] }, "$$this.placedBy", "$$REMOVE" ]
}
}
}
}
}
}
])
工作Mongo playground
关于javascript - 如何有条件地从 MongoDB 中的对象数组中删除一个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68053321/