7

I'm trying to insert multiple documents to Cosmos DB with Mongo Api which has a shard key as follows,

insertAll(trips.stream().map(t -> Document.parse(gson.toJson(t))).collect(Collectors.toList()),"trip");

insertAll method is as follows,

private void insertAll(List<Document> data, String collectionName) {
        MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
        collection.insertMany(data);
    }

And the documents I'm trying to insert are as follows,

Document{{sensorId=b827ebe942b7, liftId=1edb945b-29e7-c6c7-d20b-87c0, timestamp=1554902007838, ..............}}

Even though I'm providing the shard key which is liftId I get a exception saying single shard key must be provided.

Command failed with error 61: 'query in command must target a single shard key' on server cdb-ms-prod-southeastasia1-fd10.documents.azure.com:10255. 
    The full response is { "_t" : "OKMongoResponse", "ok" : 0, "code" : 61, "errmsg" : "query in command must target a single shard key", "$err" : "query in command must target a single shard key" }; nested exception is com.mongodb.MongoCommandException: Command failed with error 61: 'query in command must target a single shard key' on server cdb-ms-...-fd10.documents.azure.com:someport. The full response is { "_t" : "OKMongoResponse", "ok" : 0, "code" : 61, "errmsg" : "query in command must target a single shard key", "$err" : "query in command must target a single shard key" }

Any help to fix this? I'm using spring data mongodb

Martin
  • 3,096
  • 1
  • 26
  • 46
Channa
  • 3,267
  • 7
  • 41
  • 67
  • The "query in command must target a single shard key" error message is specific to CosmosDB's implementation of sharding/partitioning (which is very different from MongoDB's implementation). You haven't specified your Spring Data or Java driver versions, but a call to `insertMany` in the MongoDB driver is usually converted to a bulk write. This error message seems to suggest that bulk writes need to target a single shard. To test that theory you could try inserting a batch of documents which all have the same shard key (`liftId`) value. – Stennie Apr 11 '19 at 07:15
  • 1
    Actual I'm trying with same liftId, and even tried with single insert as well. My spring data version is `spring-data-mongodb-2.0.9` – Channa Apr 11 '19 at 08:15
  • Did you try a single insert using `insertOne()` or `insertMany()`? If only the latter, perhaps Cosmos doesn't support bulk writes into partitioned collections. If neither works I'm out of guesses for the moment :) – Stennie Apr 11 '19 at 10:31
  • yeah I tried single insert, same error – Channa Apr 12 '19 at 01:28

0 Answers0