Mongodb 在两个条件适用的情况下查询相同的文档属性
我的收藏如下:Mongodb 在两个条件适用的情况下查询相同的文档属性,mongodb,mongoose,mongodb-query,Mongodb,Mongoose,Mongodb Query,我的收藏如下: [ { testx: [ { "amount": 1, "id": "test" }, { "amount": 1, "id": "test2" } ], testy: [ { "amo
[
{
testx: [
{
"amount": 1,
"id": "test"
},
{
"amount": 1,
"id": "test2"
}
],
testy: [
{
"amount": 2,
"id": "test"
},
{
"amount": 1,
"id": "test2"
}
]
},
]
我想查找数组中两个子文档的ID相等(“testx.ID==testy.ID”)且两个子文档的“amount”属性不相等的文档
到目前为止,我试过:
find({
$where: "this.testx.id === this.testy.id && this.testx.amount !== this.testy.amount",
})
及
遗憾的是,这些人都没有返回文档。有什么建议吗?谢谢
编辑:我只想收到符合条件的文件。预期结果将是:
{
testx: {
"amount": 1,
"id": "test"
},
testy: {
"amount": 2,
"id": "test"
},
}
你必须使用操作符来实现你想要的,没有任何js代码
db.collection.find({
$and: [
{
$expr: {
$eq: [
"$testx.id",
"$testy.id"
]
}
},
{
$expr: {
$ne: [
"$testx.amount",
"$testy.amount"
]
}
}
]
})
你可以测试它。你必须使用操作符来实现你想要的,而不需要任何js代码
db.collection.find({
$and: [
{
$expr: {
$eq: [
"$testx.id",
"$testy.id"
]
}
},
{
$expr: {
$ne: [
"$testx.amount",
"$testy.amount"
]
}
}
]
})
你可以测试它。多亏@matthPen的评论,我可以用$unwind解决它
.aggregate({
$unwind: "$testx"
},
{
$unwind: "$testy"
},
{
$project: {
testx: 1,
testy: 1,
}
},
{
$match: {
$and: [
{
$expr: {
$eq: [
"$testx.id",
"$testy.id"
]
}
},
{
$expr: {
$ne: [
"$testx.amount",
"$testy.amount"
]
}
}
]
}
})
感谢@matthPen的评论,我可以用$unwind解决它
.aggregate({
$unwind: "$testx"
},
{
$unwind: "$testy"
},
{
$project: {
testx: 1,
testy: 1,
}
},
{
$match: {
$and: [
{
$expr: {
$eq: [
"$testx.id",
"$testy.id"
]
}
},
{
$expr: {
$ne: [
"$testx.amount",
"$testy.amount"
]
}
}
]
}
})
为什么testx和testy是数组?@matthPen good point,其中有多个文档,我只想接收那些适用于特定条件的文档,在数组中添加了示例文档为什么testx和testy是数组?@matthPen good point,其中有多个文档,我只想接收那些适用于特定条件的文档,将示例文档添加到数组$expr看起来非常有希望,现在的问题是,即使只有一个符合条件,数组的所有子文档都会返回。检查:我只想从适用的文档(“测试”)中接收ID。请更新您的问题:您拥有什么(包括数组中具有不同值的多个文档),以及您需要什么(数组过滤等)。您可能需要聚合框架是的,对不起,更新了问题,在不符合条件的每个数组中添加了一个文档。增加了查询的预期返回。$expr看起来很有希望,现在的问题是数组的所有子文档都会返回,即使只有一个符合条件。检查:我只想从适用的文档(“测试”)中接收ID。请更新您的问题:您拥有什么(包括数组中具有不同值的多个文档),以及您需要什么(数组过滤等)。您可能需要聚合框架是的,对不起,更新了问题,在不符合条件的每个数组中添加了一个文档。添加了查询的预期返回。