I have the following structure in the database:
{
"_id": ObjectId("6464acb09947e03e45b78b61"),
"ProjectId": "64635ac02286d48c0c0d5907",
"LabelValues": {
"62d12558d75c134f54911490": "Nicht zuzuordnen",
"62d12546d75c134f5491148f": "Nicht zuzuordnen"
},
"KnowledgeItemId": ObjectId("6464acaf9947e03e45b78b60")
}
I want to write a query, that gets this element if I pass the two ‘LabelValues’ no matter in which order.
This aggregate works:
db.knowledgeItemRelation.aggregate([
{
$match: {
$or: [
{
LabelValues: {
$all: [{"62d12558d75c134f54911490": "Nicht zuzuordnen", "62d12546d75c134f5491148f": "Nicht zuzuordnen"}]
}
}
]
}
}
])
But when the two parameters are switched, it doesn’t return a result:
db.knowledgeItemRelation.aggregate([
{
$match: {
$or: [
{
LabelValues: {
$all: [{ "62d12546d75c134f5491148f": "Nicht zuzuordnen", "62d12558d75c134f54911490": "Nicht zuzuordnen"}]
}
}
]
}
}
])
2
Answers
After several hours of trial and error and testing different approaches, I have now found one that works for me. I know that this approach does not have the best performance, but I still want to share it with you:
Playground: https://mongoplayground.net/p/cNHx1iXKnRg
On
$all
operator there is no importance to the order by definition, but$all
is for comparing arrays. You are comparing objects. When comparing objects there is no importance to the order of fields as well, regardless of the$all
operator.You can simply use:
And get the document as the result.
See how it works on the playground example