Reputation: 184
i am combing two OR queries with AND in mongoose but not getting desired result
{
_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"
}
]
}
now by mongoose query is
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
});
how i can combine two OR conditions with AND condotion ? already indexing on attributes.attributeValueM and it is working with simple AND condition given below
[ { 'attributes.attributeValueM': 'green|color' },
{ 'attributes.attributeValueM': 'metal|Frame Material' } ]
please suggest
Upvotes: 5
Views: 5112
Reputation: 545
I too had trouble with the mix of AND and OR operations. Here is a simpler example that I worked on. This code snippet did not give me the desired outcome, in other words, the right combination of AND and OR operations.
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]);
But a slight change gave me the desirable outcome:
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]);
Notice the brackets before and after recordOwner and 'company-wide-visibility'. This made the difference and gave me the desirable outcome.
Upvotes: 2
Reputation: 16805
Instead of Test.find("catID":21).and(condition)
you can use like
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
});
Upvotes: 10