如何比较数组中一个子文档的两个字段?



给定MongoDB中的一些文档

[
{
"id": 1,
"items": [
{
"id": "T0001",
"x": 10,
"y": 10
},
{
"id": "T0002",
"x": 10,
"y": 5
},
{
"id": "T0003",
"x": 10,
"y": 10
},
{
"id": "T0004",
"x": 10,
"y": 20
}
]
},
{
"id": 2,
"items": [
{
"id": "T0001",
"x": 10,
"y": 5
},
{
"id": "T0002",
"x": 10,
"y": 15
}
]
}
]

我想删除id=1文档中items.id="T0001"items.id="T0002"的子文档。这可以用下面的命令来完成。

db.collection.update({
id: 1
},
{
$pull: {
items: {
id: {
$in: [
"T0001",
"T0002"
]
}
}
}
})

但是,如果我想再添加一个条件项。X === items.y"进入$pull操作。(即只有子文档的id="T0001"将被删除,因为它的x=10y=10)

示例代码可以在这里找到https://mongoplayground.net/p/rYJp8wQPpcS。

谁能告诉我一些解决这个问题的方法?谢谢你!

使用聚合管道进行更新会更容易。

  1. $set-设置items字段。

    1.1。$filter-按条件筛选items数组:

    1.1.1。$not-否定1.1.1.1的结果。

    1.1.1.1$and—满足["T0001", "T0002"]中id的两个条件,且xy相等。

db.collection.update({
id: 1
},
[
{
$set: {
items: {
$filter: {
input: "$items",
cond: {
$not: {
$and: [
{
$in: [
"$$this.id",
[
"T0001",
"T0002"
]
]
},
{
$eq: [
"$$this.x",
"$$this.y"
]
}
]
}
}
}
}
}
}
])

Mongo Playground示例

最新更新