Node.js 使用和在Mongoose中获取两个或多个查询的结果
我在mongoose中使用AND组合了两个OR查询,但没有得到期望的结果Node.js 使用和在Mongoose中获取两个或多个查询的结果,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我在mongoose中使用AND组合了两个OR查询,但没有得到期望的结果 { _id :"23432ferf", "catId" : 21, "attributes": [ { "_id": "571237bfc02aad440c216f67", "attributeValueM": "metal|Frame Material" }, { "_id": "571237bfc02
{
_id :"23432ferf",
"catId" : 21,
"attributes": [
{
"_id": "571237bfc02aad440c216f67",
"attributeValueM": "metal|Frame Material"
},
{
"_id": "571237bfc02aad440c216f66",
"attributeValueM": "green|color"
}
]
},
{
_id :"23432ferh",
"catId" : 21,
"attributes": [
{
"_id": "571237bfc02aad440c216f67",
"attributeValueM": "metal|Frame Material"
},
{
"_id": "571237bfc02aad440c216f66",
"attributeValueM": "blue|color"
}
]
}
现在由猫鼬查询是
var condition = [
{ $or: [{ 'attributes.attributeValueM' : 'wood|Frame Material' }, { 'attributes.attributeValueM' : 'metal/Frame Material' }] },
{ $or: [{ 'attributes.attributeValueM' : 'blue|color' }, {'attributes.attributeValueM' : 'green|color'}] }
];
Test.find("catID":21).and(condition).exec(function (err, results) {
... // not getting any document
});
我如何将两个或两个条件与宽恕结合起来?
已经在attributes.attributeValue上建立索引,并且它正在使用下面给出的简单和条件
[ { 'attributes.attributeValueM': 'green|color' },
{ 'attributes.attributeValueM': 'metal|Frame Material' } ]
请建议而不是测试。查找(“catID”:21)。和(条件)
您可以像这样使用
Test.find({
$and: [
{ catID:21 },
{ $or: [{ "attributes.attributeValueM" : 'wood|Frame Material' }, { "attributes.attributeValueM" : 'metal/Frame Material' }] },
{ $or: [{ "attributes.attributeValueM" : 'blue|color' }, {"attributes.attributeValueM" : 'green|color'}] }
]
}).exec(function (err, results) {
// rest of code
});
我在和以及或操作的混合中也遇到了麻烦。这里有一个更简单的例子。这个代码片段没有给我期望的结果,换句话说,和以及或操作的正确组合
awTextsDocuments = await AWTextModel
.find({
$and: [
{ name: { $regex: reqObj.q, $options: 'i' } },
{ $or: [ recordOwner: req.user._id, 'company-wide-visibility': { $in:
true } ] },
],
})
.skip(reqObj.offset)
.limit(reqObj.limit)
.sort([mongoSortQuery]);
但一个小小的变化给了我一个理想的结果:
awTextsDocuments = await AWTextModel
.find({
$and: [
{ name: { $regex: reqObj.q, $options: 'i' } },
{ $or: [{ recordOwner: req.user._id }, { 'company-wide-visibility': { $in:
true } }] },
],
})
.skip(reqObj.offset)
.limit(reqObj.limit)
.sort([mongoSortQuery]);
请注意,记录所有者和公司范围内的可见性前后的括号。这就产生了不同,给了我理想的结果。你想要这样(A&&((B | | C)和&(D | | E))?不清楚你期望得到什么结果。是否希望此处提供的两个文档都与查询匹配?如果您演示了您都希望与条件匹配和不匹配的文档,这会更清楚,因为您编写查询的方式显然不起作用。如果我的或和查询中的条件是动态的,那么我如何才能获得相同的结果