如何根据 MongoDB 中的 ID 从多个集合中删除文档? [英] How to remove documents from multiple collections based on ID in MongoDB?

查看:55
本文介绍了如何根据 MongoDB 中的 ID 从多个集合中删除文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个集合;架构如下-

I have two collections; schema as follows-

posts
 - ID
 - author
 - title
 - content

user_posts
 - ID
 - post_id
 - user_id

在 SQL 中,我可以一次从两个表中删除一个条目,例如

In SQL I could delete an entry from two tables at a time like

DELETE posts, user_posts
FROM posts
INNER JOIN user_posts
ON posts.ID = user_posts.post_id
WHERE posts.ID = 102

我怎样才能为 Mongodb 实现上述类似的代码?我知道如何从单个集合中删除一个条目.一种解决方案是使用回调一个接一个地执行删除操作以确保操作成功,但我想一次从两个集合中删除文档.

我提到了这个使用meteorjs的解决方案但我对Mongo很陌生所以我无法理解.而此解决方案适用于所有人 当前数据库中存在的集合,但我只有这两个与此操作相关的集合,其他的则不相关.任何帮助将不胜感激.

How can I achieve above similar code for Mongodb? I know how to delete an entry from single collection. One solution is to perform remove operation one after the other using callbacks for the surety of successful operation but I want to remove documents from both collections at a time.

I referred this solution using meteor but I'm quite new to Mongo so I could'nt understand it. Whereas this solution is for all the collections present in the current database but I have only these two collections related to this operation others are unrelated. Any help will be appreciated.

推荐答案

目前,这根本不可能.为了访问两个集合,您必须使用聚合框架,但是在此阶段无法执行任何数据操作.此外,一次"要求将需要支持目前仅在 Beta 版中可用的交易 - 所以,再次倒霉.

Currently, this is simply not possible. In order to access two collections you'd have to use the aggregation framework which, however, cannot perform any data manipulations at this stage. Plus, the "at a time" requirement would require support for transactions which is only available in a beta version right now - so again, bad luck.

底线是:您建议的回调方法是可行的方法.

Bottom line is: Your suggested approach with the callback is the way to go.

这篇关于如何根据 MongoDB 中的 ID 从多个集合中删除文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆