6565 */
6666class MongoCopyDataManager implements AutoCloseable {
6767 private static final Logger LOGGER = LoggerFactory .getLogger (MongoCopyDataManager .class );
68- static final String NAMESPACE_FIELD = "__" ;
69- private static final byte [] NAMESPACE_BYTES = "ns" .getBytes (StandardCharsets .UTF_8 );
68+ private static final String NAMESPACE_FIELD = "ns" ;
69+ static final String ALT_NAMESPACE_FIELD = "__" ;
70+ private static final byte [] NAMESPACE_BYTES = NAMESPACE_FIELD .getBytes (StandardCharsets .UTF_8 );
7071
7172 private static final String PIPELINE_TEMPLATE =
7273 format (
@@ -80,6 +81,12 @@ class MongoCopyDataManager implements AutoCloseable {
8081 + "}" ,
8182 NAMESPACE_FIELD );
8283
84+ private static final BsonDocument ADD_ALT_NAMESPACE_STAGE =
85+ BsonDocument .parse (
86+ format ("{'$addFields': {'%s': '$%s'}}" , ALT_NAMESPACE_FIELD , NAMESPACE_FIELD ));
87+ private static final BsonDocument UNSET_ORIGINAL_NAMESPACE_STAGE =
88+ BsonDocument .parse (format ("{'$project': {'%s': 0}}" , NAMESPACE_FIELD ));
89+
8390 private volatile boolean closed ;
8491 private volatile Exception errorException ;
8592 private final AtomicInteger namespacesToCopy ;
@@ -187,6 +194,8 @@ static List<Bson> createPipeline(final MongoSourceConfig cfg, final MongoNamespa
187194 BsonDocument .parse (
188195 format (PIPELINE_TEMPLATE , namespace .getDatabaseName (), namespace .getCollectionName ())));
189196 cfg .getPipeline ().map (pipeline ::addAll );
197+ pipeline .add (ADD_ALT_NAMESPACE_STAGE );
198+ pipeline .add (UNSET_ORIGINAL_NAMESPACE_STAGE );
190199 return pipeline ;
191200 }
192201
@@ -196,7 +205,7 @@ static RawBsonDocument convertDocument(final RawBsonDocument original) {
196205 int currentPosition = 0 ;
197206 reader .readStartDocument ();
198207 while (reader .readBsonType () != BsonType .END_OF_DOCUMENT ) {
199- if (reader .readName ().equals (NAMESPACE_FIELD )) {
208+ if (reader .readName ().equals (ALT_NAMESPACE_FIELD )) {
200209 currentPosition ++; // Adjust the current position to include the bson type
201210 byte [] sourceBytes = sourceBuffer .array ();
202211 // Convert the namespace field in situ
0 commit comments