skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    db.collection.aggregate([
      {
        $match: {
          $or: [
            {
              $and: [
                {
                  "LabelValues.62d12558d75c134f54911490": "Nicht zuzuordnen"
                },
                {
                  "LabelValues.62d12546d75c134f5491148f": "Nicht zuzuordnen"
                },
                
              ]
            }
          ]
        }
      }
    ])
    

    Playground: https://mongoplayground.net/p/cNHx1iXKnRg


  2. 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:

    db.collection.aggregate([
      {
        $match: {
          LabelValues: {
            "62d12546d75c134f5491148f": "Nicht zuzuordnen",
            "62d12558d75c134f54911490": "Nicht zuzuordnen"
          }
        }
      }
    ])
    

    And get the document as the result.

    See how it works on the playground example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search