title: How to delete many documents in a partitioned collection in Azure CosmosDB using MongoDB API
body: <p>Consider the following document type</p>
  
  <pre><code>class Info
  {
      public string Id { get; set; }
      public string UserId { get; set; }  // used as partition key
      public DateTime CreatedAt { get; set; }
  }
  </code></pre>
  
  <p>I've created a collection using this</p>
  
  <pre><code>var bson = new BsonDocument
  {
      { "shardCollection", "mydb.userInfo" },
      { "key", new BsonDocument(shardKey, "hashed") }
  };
  database.RunCommand(new BsonDocumentCommand&lt;BsonDocument&gt;(bson));
  </code></pre>
  
  <p>To delete all documents that are older than a certain date, I tried this</p>
  
  <pre><code>collection.DeleteManyAsync(t =&gt; t.CreatedAt &gt;= date);
  </code></pre>
  
  <p>But this fails with <code>Command delete failed: query in command must target a single shard key.</code> My question is, how should I efficently delete these documents across multiple partitions? I'm not looking for answers how to choose the partition key in this case. I think that there will be always cases where I have to run modifiying queries across all partitions.</p>
  
  <p>I could first query for documents with <code>collection.Find(t =&gt; t.CreatedAt &gt;= date)</code> and then run a <code>DeleteManyAsync(t =&gt; idsInThatPartition.Contains(t.Id) &amp;&amp; t.UserId == thatPartitionKey)</code> for each group of partition key, but I really hope that there is a better way. Example code:</p>
  
  <pre><code>var affectedPartitions = await collection.Aggregate()
      .Match(i =&gt; i.CreatedAt &gt;= date)
      .Group(i =&gt; i.UserId, group =&gt; new { Key = group.Key })
      .ToListAsync();
  
  foreach (var partition in affectedPartitions)
  {
      await collection.DeleteManyAsync(
          i =&gt; i.CreatedAt &gt;= date &amp;&amp; i.UserId == partition.Key);
  }
  </code></pre>