英文:
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
以下是您要翻译的内容:
这可以通过聚合管道来完成。例如:
- 您的查询示例(可以是您需要的步骤数)
- 计算所有结果文档的数量并创建一个文档
- 仅在计数小于N时保留该文档
- 用要插入的文档替换
- 格式化它
- 插入到集合中(如果条件不满足,将不会插入任何内容)
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:
- An example of your query (which can be how many steps you need)
$count
all results documents and create one document- Keep the document only if the count is less than N
- Replace with the doc you want to insert
- Format it
- 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论