I have a collection of documents like this in a mongo db :
"_id" : ObjectId("592bc37c339e7a23788b4c7c"),
"trips" : [
{
"tripGcsId" : "5937f86e339e7a2a58ac3186",
"tripCounter" : NumberLong(1283),
"tripRef" : "hjkhjk"
},
{
"tripGcsId" : "5937f914339e7a2a58ac318b",
"tripCounter" : NumberLong(1284),
"tripRef" : "fjh"
}
]
and a method on the server side (Spring+Mongo):
public List<String> removeTripObject( List<String> tripIds )
{
Query query = Query.query( Criteria.where( "trips" ).elemMatch( Criteria.where( "tripGcsId" ).in( tripIds ) ) );
Update update = new Update().pullAll( "trips.tripGcsId", new Object[] { tripIds } );
getMongoTemplate().updateMulti( query, update, "ORDER" );
return updatedOrders;
}
The parameter tripIds
is a list of tripGcsIds to be removed from trips array. The method above gives me the error: Write failed with error code 16837 and error message 'cannot use the part (trips of trips.tripGcsId) to traverse the element.
When I try with the $ operator, as described in other SO answers like this:
public List<String> removeTripObject( List<String> tripIds )
{
Query query = Query.query( Criteria.where( "trips" ).elemMatch( Criteria.where( "tripGcsId" ).in( tripIds ) ) );
Update update = new Update().pullAll( "trips.$.tripGcsId", new Object[] { tripIds } );
getMongoTemplate().updateMulti( query, update, "ORDER" );
return updatedOrders;
}
i got this error: Write failed with error code 16837 and error message 'Can only apply $pullAll to an array.
I'm not sure how should this pullAll command look like on the server side.
You need to use $pull
update operator which takes the query to match and delete all the matching rows in embedded array.
Something like
public List<String> removeTripObject( List<String> tripIds ) {
Query query = Query.query( Criteria.where( "tripGcsId" ).in( tripIds ) );
Update update = new Update().pull("trips", query );
getMongoTemplate().updateMulti( new Query(), update, "ORDER" );
return updatedOrders;
}
Reference
来源:https://stackoverflow.com/questions/44413686/remove-items-from-array-of-documents-in-springmongo