0

I have an array of arrays in MongoDB 4.2.2:

db.foo.insertOne({'foo': [[1, 3], [2], [3]]})

I'd like to remove elements of foo, first elements of which are greater than 1. But I cannot figure out how.

I tried something like this (and many more) but it does not pull anything:

db.foo.update({}, {$pull: {foo: {'0': {$gt: 1}}}})

Is it possible?

EDIT: Expected result:

db.foo.find({})
{ "_id": ObjectId("..."), "foo": [ [1, 3] ] }
3
  • Can you show what you expect the document to look like after this operation? I think it will help make clear your intent. Commented Feb 13, 2020 at 16:28
  • How do you apply "which are greater than 1" on an array? Do you consider the Array [1,3] greater than 1? If yes, what are the exact conditions for that? Commented Feb 13, 2020 at 16:45
  • @JamesWahlin sorry, I've edited my answer. @WernfriedDomscheit "first elements of which are greater than 1" i.e. I compare the first elements, so [1, 3] does not hold the condition. Commented Feb 14, 2020 at 9:11

1 Answer 1

1

If you are using MongoDB 4.2, you can make use of a pipeline in the new update. This allows you to pass an aggregation pipeline as the update argument:

db.foo.update({},[
    {$addFields:{
        foo:{
            $filter:{
                input:"$foo",
                cond:{
                    $lte: [{$arrayElemAt: ["$$this", 0]}, 1]
                }
            }
        }
    }}
  ])
Sign up to request clarification or add additional context in comments.

4 Comments

Great! So the "$$this" keyword can address the top level. Btw, after "$$this" there should be comma instead of period (I cannot edit it because it's only 1 character and I need 6). @Joe, maybe you can?
wait... it behaves weirdly on some inputs, I need to test it more... Ok, got it, editing your answer.
and if you want to use a name other than this, you can specify an as field to the filter with the name you want.
There are few more incompatibilities with my question, the line should be $lte: [{$arrayElemAt: ["$$this", 0]}, 1]. My edit was not accepted for some reason, @Joe, could you please fix it so that I could mark your answer again as accepted?

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.