mongodb - 如何找到 splinter 的 "Foreign Key"关系的等价物?

标签 mongodb mongodb-query

如果这是一个关系数据库,我有两个集合,我们称之为“一对一关系”。我不知道为什么一个不嵌套在另一个中,但事实是对于集合“A”中的每个文档,集合“B”中都有一个文档,反之亦然。

当然,在没有外键约束且存在错误的情况下,有时“A”中的文档在“B”中没有相关文档(反之亦然)。

我是 MongoDB 的新手,我在创建查询或脚本时遇到了麻烦,这些查询或脚本会找到“A”中的所有文档,而这些文档在“B”中没有相关文档(反之亦然)。我想我可以使用某种循环,但我还不知道它是如何工作的——我才刚刚开始在 RoboMongo 命令行上使用简单的查询。

任何人都可以让我开始使用脚本吗?我看过“Verifying reference (foreign key) integrity in MongoDB”,但这对我没有帮助。一个错误导致“参照完整性”崩溃,我需要脚本来帮助我追踪错误。我也无法重新设计数据库以使用嵌入(尽管我希望我会问为什么一个文档没有嵌套在另一个文档中)。

我也看到了“How to find items in a collections which are not in another collection with MongoDB”,但是没有答案。

糟糕技术的伪代码

var misMatches = [];
var collectionB = db.getCollection('B');
var allOfA = db.getCollection('A').find();
while (allOfA.hasNext()) {
    var nextA = allOfA.next();
    if (!collectionB.find(nextA._id)) {
        misMatches.push(nextA._id);
    }
}

最佳答案

我不知道这是否适用,但是......

...给定这个示例日期集:

> db.a.insert([{a:1},{a:2},{a:10}       ])
> db.b.insert([      {b:2},{b:10},{b:20}])
//             ^^^^^              ^^^^^^
//                inconsistent 1-to-1 relationship

您可以使用 map-reduce 收集 a 中的键集,并将其与 b 中的键集合并:

mapA=function() {
  emit(this.a, {col: ["a"]})
}

mapB=function() {
  emit(this.b, {col: ["b"]})
}

reduce=function(key, values) {
  // merge both `col` arrays; sort the result
  return {col: values.reduce(
                 function(a,b) { return a.col.concat(b.col) }
                            ).sort()}
}

制作:

> db.a.mapReduce(mapA, reduce, {out:{replace:"result"}})
> db.b.mapReduce(mapB, reduce, {out:{reduce:"result"}})
> db.result.find()
{ "_id" : 1, "value" : { "col" : [ "a" ] } }
{ "_id" : 2, "value" : { "col" : [ "a", "b" ] } }
{ "_id" : 10, "value" : { "col" : [ "a", "b" ] } }
{ "_id" : 20, "value" : { "col" : [ "b" ] } }

然后很容易找到集合 ab 中没有找到的所有 id。此外,您应该能够在一个或另一个集合中发现重复键:

> db.result.find({"value.col": { $ne: [ "a", "b" ]}})
{ "_id" : 1, "value" : { "col" : [ "a" ] } }
{ "_id" : 20, "value" : { "col" : [ "b" ] }

关于mongodb - 如何找到 splinter 的 "Foreign Key"关系的等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30408471/

相关文章:

mongodb - 无法在 mongodb 中创建索引, "key too large to index"

mongodb - 如何维护 mongoDB 中数组元素的最高计数?

javascript - 查询引用文档的字段

javascript - 是否有另一种方法可以在此函数之外关闭 MongoDB 连接?

mongodb - MongoDB 聚合查询

mongodb - 如何将数据库从 mongolab.com 复制或导入到我的本地 mongodb 服务器?

node.js - MongooseError - 操作 `users.findOne()` 缓冲在 10000 毫秒后超时

mongodb - 在查询中可以传递给 MongoDB '$in' 运算符的数组元素的数量有什么限制?

java - 哪些工具可用于将测试数据填充到 mongodb

php - 在浏览器上显示保存在 gridfs 中的 pdf 文件的预览