我在mongo db中有这样的文档集合:
"_id" : ObjectId("592bc37c339e7a23788b4c7c"), "trips" : [ { "tripGcsId" : "5937f86e339e7a2a58ac3186", "tripCounter" : NumberLong(1283), "tripRef" : "hjkhjk" }, { "tripGcsId" : "5937f914339e7a2a58ac318b", "tripCounter" : NumberLong(1284), "tripRef" : "fjh" } ]
和服务器端的方法(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.
tripIds
Write failed with error code 16837 and error message 'cannot use the part (trips of trips.tripGcsId) to traverse the element.
当我尝试使用$运算符时,如其他SO所述,答案如下:
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.
Write failed with error code 16837 and error message 'Can only apply $pullAll to an array.
我不确定这个pullAll命令在服务器端应该是什么样子。
您需要使用$pull更新运算符,该运算符将查询用于匹配并删除嵌入式数组中的所有匹配行。
$pull
就像是
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; }
参考
https://docs.mongodb.com/manual/reference/operator/update/pull/#remove-items- from-an-array-of- documents