Collection can't find match result ,but document will be update later

Hi ,
I created a new collection to test MQL .

db.test.insert({test_array:[1 ,2 ,3 ,[4 ,5]]});
db.test.find({test_array:{$in:[5] }}) ;

no result

db.test.update( {},{$pull:{test_array:{$in:[5] }}} ) ;

document has been modified

I don’t know why this update statement will modify this document ?
Thanks.

In you test array you have no element with the value 5. The value 5 is part of a sub-array. If you run

c.find( { test_array : { "$in" : [ 3 ]}})

you will get

{ _id: 0, test_array: [ 1, 2, 3, [ 4, 5 ] ] }

As for the update, the {} indicates to modify all documents. Your $pull applies the expression {$in:[5]} to all elements of the array to determine which elements to $pull. The expression {$in:[5]} being true for the sub-array [4,5], the element [4,5] is removed from test_array.

Hi ,
If the document like below:

db.test.insert({test_array:[1 ,2 ,3 ,5 ,[4 ,5]]});

The update will pull out the 5 and [4,5] elements, but why the sub-array will be pull out all ,not only one element?

db.test.update( {},{$pull:{test_array:{$in:[5] }}} ) ;

If I want to pull out the match element in sub-array ,not all sub-array ,how could I do it ?

All elements of test_array for which the expression {$in:[5]} is true. The expression is true for the value 5 and it is also true for the array [4,5].

You could remove the value 5 from test_array with

{ "$pull" : { test_array : 5 } }

the element [4,5] is untouched because it is not equal to 5.

As for

I do not know yet, but you might need to update with an aggregation pipeline using $map.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.