Mongo只在文档总数小于N时插入。

huangapple go评论50阅读模式
英文:

Mongo insert only if total document count is less than N

问题

我想要将文档插入MongoDB,只有当我的查询返回的总数小于某个特定的阈值N时才能插入。这种类型的查询在MongoDB中是否可能,或者我应该转向关系数据库,在那里可以在查询中使用CASE和WHERE约束来处理这种情况。

我正在寻找一种解决方案,其中这种类型的插入将会以高规模和并发方式发生,但插入阈值不应被超过。

我在关系数据库中找到了这种解决方案,还在进行使用存储过程(SP)的POC以查看是否可以处理此问题。

提前感谢您。

英文:

I want to insert a document into mongo only if the total count returned by my query is less than a certain threshold number N. Is this kind of query possible in mongodb or should I switch to relational databases where this can be handled with case and where constraints in the query.

I am looking for a solution where these kind of insertions would happen at high scale and concurrency, and still the insertion threshold should not get exceeded.

I could find this kind of solution in relational databases, also doing a POC with SP(Stored Procedures) to find if this can be handled.

Thanks in Advance.

答案1

得分: 0

以下是您要翻译的内容:

这可以通过聚合管道来完成。例如:

  1. 您的查询示例(可以是您需要的步骤数)
  2. 计算所有结果文档的数量并创建一个文档
  3. 仅在计数小于N时保留该文档
  4. 用要插入的文档替换
  5. 格式化它
  6. 插入到集合中(如果条件不满足,将不会插入任何内容)
db.collection.aggregate([
  {$match: {您的查询}},
  {$count: "count"},
  {$match: {count: {$lt: N}}},
  {$project: {doc: 新文档}},
  {$replaceRoot: {newRoot: "$doc"}},
  {$merge: {into: "collection"}}
])

播放示例上查看它是如何工作的。

英文:

It can be done using an aggregation pipeline. For example:

  1. An example of your query (which can be how many steps you need)
  2. $count all results documents and create one document
  3. Keep the document only if the count is less than N
  4. Replace with the doc you want to insert
  5. Format it
  6. Insert into the collection (if the condition is not met, nothing will be inserted)
db.collection.aggregate([
  {$match: {your query}},
  {$count: "count"},
  {$match: {count: {$lt: N}}},
  {$project: {doc: newDoc}},
  {$replaceRoot: {newRoot: "$doc"}},
  {$merge: {into: "collection"}}
])

See how it works on the playground example

huangapple
  • 本文由 发表于 2023年5月8日 02:08:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76195529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定