具有两个集合和where子句的mongodb类似联接的查询 [英] mongodb join-like query with two collections and a where clause

查看:125
本文介绍了具有两个集合和where子句的mongodb类似联接的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们在数据库中有以下集合:

Suppose we have following collections in a database:

db.documents.insert([{'name': 'A'}, {'name': 'B'}, {'name': 'C'}])
db.fragments.insert([{'value:': 'A1', doc_name: 'A'}, {'value:': 'A2', doc_name: 'A'},
                     {'value:': 'B1', doc_name: 'B'}, {'value:': 'B2', doc_name: 'B'},
                     {'value:': 'C1', doc_name: 'C'}, {'value:': 'C2', doc_name: 'C'}])

其中documents集合存储文档的名称(此示例中省略了其他内容),而fragments集合由doc_name引用与该片段相关的文档.

where documents collection stores the names of the documents (and other stuff omitted in this example), fragments collections refers by doc_name to a document related to the fragment.

现在,如果我只想考虑文档的子集

Now, if I only want to consider a subset of documents

> db.documents.find().limit(2)
{ "_id" : ObjectId("52d1a3bf49da25160ad6f076"), "name" : "A" }
{ "_id" : ObjectId("52d1a3bf49da25160ad6f077"), "name" : "B" }

然后我如何查看与这些选定文档相关的片段,所以我会得到

then how can I see the fragments of associated to these selected documents, so I would get

{ "_id" : ObjectId("52d1a3bf49da25160ad6f079"), "value:" : "A1", "doc_name" : "A" }
{ "_id" : ObjectId("52d1a3bf49da25160ad6f07a"), "value:" : "A2", "doc_name" : "A" }
{ "_id" : ObjectId("52d1a3bf49da25160ad6f07b"), "value:" : "B1", "doc_name" : "B" }
{ "_id" : ObjectId("52d1a3bf49da25160ad6f07c"), "value:" : "B2", "doc_name" : "B" }


作为一种解决方案,我认为我应该将文档名称存储在数组中,例如var docnames = ???这样的


As a solution, I was thinking that I should store the document names in an array, something like var docnames = ??? such that

> docnames
[ "A", "B" ]

,然后尝试在where子句中使用此数组,例如

and then trying to use this array in a where clause, something like

> db.fragments.find({$where: function(x) { return (this.doc_name in docnames)}})
error: {
        "$err" : "ReferenceError: docnames is not defined near 'c_name in docnames)}' ",
        "code" : 16722
}

但是由于我对mongodb并不陌生,所以我很难弄清楚.我相信这也可以单线完成.

But as I am very new to mongodb, so I am having trouble figuring it out. I believe this could be done as a one-liner as well.

推荐答案

db.fragments.find( { 'doc_name': { $in : ['A' , 'B'] } } ); 

mongo中执行以下命令:

var f = db.documents.find().limit(2) , n = [];
for (var i = 0; i < f.length(); i++) n.push(f[i]['name']);
db.fragments.find( { 'doc_name': { $in : n } } ); 

这篇关于具有两个集合和where子句的mongodb类似联接的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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