验证MongoDB中的参考(外键)完整性 [英] Verifying reference (foreign key) integrity in MongoDB

查看:69
本文介绍了验证MongoDB中的参考(外键)完整性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过将B's ObjectId存储在A中(例如A.bId)来链接两个MongoDB集合,例如AB.如何找到A的所有实例,其中bId不再有效(对应的B不存在)?

I'm linking two MongoDB collections, say A and B, by storing B's ObjectId in A (say A.bId). How do I find all instances of A, where bId no longer valid (the corresponding B doesn't exist)?

基于答案官方文档,很明显MongoDB不强制执行引用.因此,我需要一种有效的方法来查找无效的A's以便清除它们.

Based on answers and official documentation, it's clear that MongoDB doesn't enforce references. So I need an efficient way to find invalid A's in order to purge them.

AB是大集合,因此我想避免:

A and B are large collections, so I'd like to avoid:

  • 将所有B.id's加载到内存中并执行$nin
  • 遍历所有A's并执行B.findById(A.bId)
  • Loading all B.id's into memory and doing a $nin
  • Iterating through all A's and do B.findById(A.bId)

推荐答案

我将通过编写我的应用程序代码来解决此问题,以便A中的所有无效文档一经失效就被删除.这与您编写脚本以同时查找和删除A中所有无效文档的想法不同.

I would solve this by writing my application code so that any invalid documents in A are removed as soon as they become invalid. This is different than your idea of writing a script to find and remove all invalid documents in A at the same time.

第一步是问自己"A集合中的文档在什么时候可以失效?"说答案是每当从B集合中删除文档时."然后,我将编写一个函数来运行删除后操作,以删除A中的所有无效文档.如果正确设置文档结构和索引,则可以快速完成此操作.

The first step would be asking yourself "At what point(s) in my application can a document in the A collection become invalid?" Say the answer is "Whenever a document from the B collection is removed." Then I would code a function to run post-delete to remove any invalid documents in A. This can be done quickly if you set up the document structure and indexes correctly.

问自己一个更大的问题是,如果您要引用另一个集合中的数据,并且需要经常加入这些数据,则可能是您的数据模型在MongoDB中的结构不是很有效.或者,也许您应该完全转向关系数据库系统.

The bigger question to ask yourself is, if you're referencing data in one collection from another, and needing to JOIN that data frequently, perhaps your data models aren't structured in an efficient way in MongoDB. Or perhaps you should move completely over to a relational database system.

这篇关于验证MongoDB中的参考(外键)完整性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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