在Spring + Mongo中从文档数组中删除项目 [英] Remove items from array of documents in Spring+Mongo
问题描述
我在mongo db中有这样的文档集合:
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"
}
]
和服务器端的方法(Spring + Mongo):
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;
}
参数tripIds
是要从trips数组中删除的tripGcsId的列表.上面的方法给我错误:Write failed with error code 16837 and error message 'cannot use the part (trips of trips.tripGcsId) to traverse the element.
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.
当我尝试使用$运算符时,如其他SO答案中所述:
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;
}
我收到此错误:Write failed with error code 16837 and error message 'Can only apply $pullAll to an array.
我不确定这个pullAll命令在服务器端应该是什么样子.
I'm not sure how should this pullAll command look like on the server side.
推荐答案
您需要使用$pull
update运算符,该运算符将查询用于匹配并删除嵌入式数组中的所有匹配行.
You need to use $pull
update operator which takes the query to match and delete all the matching rows in embedded array.
类似
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;
}
参考
这篇关于在Spring + Mongo中从文档数组中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!