1

In my collection, all of my documents have an array called tags:

"tags" : [
        {
            "name" : "a", 
            "weight" : NumberInt(32)
        }, 
        {
            "name" : "b", 
            "weight" : NumberInt(26)
        }, 
        {
            "name" : "c", 
            "weight" : NumberInt(25)
        }, 
        ...
]

Each object in the array has keys name and weight. I need to remove the weight key, so that I'm just left with the names in an single-level array like ["a", "b", "c"...]


An explanation of why I need to do this:

Inside my aggregation, I want to calculate the number of matches between an array x = ["a", "b", "d"] and whatever tags each document has.

This is as far as I've gotten- inside a $project I create a new variable like so:

"$project": {
    ...
    "diff": {
       "$size": {
          "$setIntersection": [ x, "$tags" } ]
       }
    },
    ...
}

But of course this doesn't work as the $tags array is full of objects, and not strings. I need to strip the weight from the tags array and leave it just as an array of names like ["a", "b", "c" ...], then it should work.

How would I go about doing this?

0

1 Answer 1

1

Just use . dot notation with the name inside tags. Something like

db.collection.aggregate([
  { "$project": {
    "matches": {
      "$size": {
        "$setIntersection": [
          [ "a", "b", "d"],
          "$tags.name"
        ]
      }
    }
  }}
])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it works perfectly. I didn't expect it to be so simple

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.