1

I have a mongo collection with objects like these:

[
{
    "_id" : "a2d",
    "entityType" : "Location",
    "type" : "STRING",
},
{
    "_id" : "a1_order",
    "entityType" : "Order",
    "type" : "STRING",
}
]

Trying to append the _entityType to all document's id where it is not present at the end id the id (the first object in the above case).

Using mongo with Spring, but I'm already stuck with the first step, to get all the objects with no entityType in id.

Thinking about something like this, with regex, but I'm not sure how should it look like:

Query query = new Query();
query.addCriteria( Criteria.where( "id" ).regex( "here i need the entity type of the current document" ) );

2 Answers 2

2

You can build your regex by '^' ('starts with' Regex).

So you need a function who point in all documents and check this filter

    List<Document> result = new ArrayList<Document>();
    StringBuilder idPrefix = new StringBuilder();
    idPrefix.append("^");
    idPrefix.append(idCode);
    idPrefix.append("_");
    List<Bson> filters = new ArrayList<Bson>();
    filters.add(Filters.regex("_id", keyPrefix.toString()));
    for (Document d : yourCollections.find(Filters.and(filters)))
        list.add(d);
Sign up to request clarification or add additional context in comments.

Comments

1

You actually want a "reverse regex" here, as you need to use the data in the document in order to match on another field.

Presently you can really only do this with MongoDB using $where, which evaluates JavaScript on the server. So for spring mongo, you need the BasicQuery instead, so we can construct from BasicDBObject and Code primatives:

    BasicDBObject basicDBObject = new BasicDBObject("$where",
            new Code("!RegExp('_' + this.entityType + '$','i').test(this.id)"));

    BasicQuery query = new BasicQuery(basicDBObject);

That will test the "id" field in the document to see if it matches the value from entityType at the "end of the string" and without considering "case". The ! is a Not condition, so the "reverse" of the logic is applied to "not match" where the field actually did end that way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.