从 Spring+Mongo 中的文档数组中删除项目

Remove items from array of documents in Spring+Mongo

我在 mongo 数据库中收集了这样的文档:

"_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.

当我尝试使用 $ 运算符时,如其他 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.

我不确定这个 pullAll 命令在服务器端应该是什么样子。

您需要使用 $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