John
John

Reputation: 1

using mongo $toObjectId function in java driver aggregation

I am using a Mongo java driver (version 3.12.12) aggregation to join two MongoDB collections.

The left side collection has a string version of the right side collection's _id field. Here are some sample docs:

leftCollection:

{ "foreignKey" : "5a43b24cb4eac10001dbafba"}

rightCollection:

{ "_id" : ObjectId("5a43b24cb4eac10001dbafba", "rightsideField": "some right side stuff")}

I need to transform the leftCollection.foreignKey strings into ObjectIds so that I can use that objectId as the foreign key in a later $lookup stage. I'm trying to use the $toObjectId mongo aggregation function for that purpose.

Here's the code that does that:

    Bson addForeignKeyObjectId = Aggregates.addFields(new Field("foreignKeyObjId", "$toObjectId:\"$foreignKey\""));

    List<BsonDocument> foo = ImmutableList.copyOf(leftCollection.aggregate(
          ImmutableList.of(
            addForeignKeyObjectId,
          )
      ))

what I'm expecting:

{"foreignKey":"5a43b24cb4eac10001dbafba", "foreignKeyObjId":ObjectId("5a43b24cb4eac10001dbafba")}

what I get:

{"foreignKey":"5a43b24cb4eac10001dbafba"}

Note the desired foreignKeyObjId field is not added. :(

However, if I replace the $toObjectId expression with a literal like this:

Bson addForeignKeyObjectId = Aggregates.addFields(new Field("foreignKeyObjId", "some bogus literal"));

the new fields are added correctly and the output documents look like this:

{"foreignKey":"5a43b24cb4eac10001dbafba", "foreignKeyObjId":"some bogus literal"}

So, the addFields aggregation step appears to be working correctly, but I suspect I haven't got the syntax of the $toObjectId expression quite right. Can anyone hint me to the right move here?

(I really really wish we weren't using _ids as foreign keys, everything becomes harder with that approach, but do not have the scope to change this ugliness rn)

Upvotes: 0

Views: 43

Answers (1)

Joe
Joe

Reputation: 28316

You are adding a string instead of an object. The string "$toObjectId:\"$foreignKey\"" means to take the value of the field toObjectId:"$foreignKey". Since that value is missing/undefined, the "created" field is also missing/undefined.

Instead of a string, create an object with a field named $toObjectId and value "$foreignKey"

Upvotes: 0

Related Questions