Remove items from array of documents in Spring+Mongo

妖精的绣舞 提交于 2019-12-20 04:13:29

问题


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.


回答1:


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://docs.mongodb.com/manual/reference/operator/update/pull/#remove-items-from-an-array-of-documents



来源:https://stackoverflow.com/questions/44413686/remove-items-from-array-of-documents-in-springmongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!