user8152821
user8152821

Reputation: 187

Query by Id in MongoTemplate Fails Due to Conversion to $oid

I have a simple operation to remove a document from MongoDB using MongoTemplate. The reason for using MongoTemplate is because the project is not directly associated with the service utilizing the database, hence it does not require, and should not require, the database model classes itself.

The query is as follows:

Criteria criteria = Criteria.where("_id")
        .is(new ObjectId(id));
      mongoTemplate.remove(Query.query(criteria), collectionName);

Where id is a String object, and collectionName is the name of the collection.

However, the query, when translated to MongoDB syntax by Spring Data MongoDB, produces such expression: { "_id" : { "$oid" : "5e206994943f3c1d6c778efb"}} instead of { "_id" : ObjectId("5e206994943f3c1d6c778efb")}.

As a result, the data persists in the database, even though it should be removed. When I try the former query on Mongo shell itself, it throws the error of Unknown operator: $oid.

Is there anything wrong that I did? How to fix them?

Thank you.

Upvotes: 1

Views: 2319

Answers (3)

happybull
happybull

Reputation: 11

you could do this: custom a class extends MappingMongoConverter, and overwrite method convertId(Object id, Class<?> targetType). like this:

@Override
    public Object convertId(Object id, Class<?> targetType) {
        if (id == null || ClassUtils.isAssignableValue(targetType, id)) {
            return id;
        }

        if (ClassUtils.isAssignable(ObjectId.class, targetType)) {

            if (id instanceof String) {

                if (ObjectId.isValid(id.toString())) {
                    return id.toString();
                }
            }
        }

        try {
            return getConversionService().canConvert(id.getClass(), targetType)
                    ? getConversionService().convert(id, targetType)
                    : convertToMongoType(id, null);
        } catch (ConversionException o_O) {
            return convertToMongoType(id, null);
        }
    }

Upvotes: 1

user12765267
user12765267

Reputation: 11

From Spring Data mongodb 2.2.X @Id operator changed with @MongoId operator.

I used like this and resolved.

Mongodb collection data :

_id: ObjectId('5e1f1bf501eb6332ebf8664c')

Spring data solution:

@MongoId(targetType = FieldType.OBJECT_ID)
private String id;

Upvotes: 1

user8152821
user8152821

Reputation: 187

I finally was able to fix this by using MongoDatabase instead. By using the method deleteOne I was able to delete by _id with creating new ObjectId(id), wrapped under BasicDBObject.

Upvotes: 2

Related Questions