将条件应用于MongoDB中同一字段的多个文档 [英] Applying condition to multiple documents for the same field in MongoDB
问题描述
我有一个具有以下结构的文档:
I have a documents with the following structure:
user {id: 123, tag:"tag1"}
user {id: 123, tag:"tag2"}
user {id: 123, tag:"tag3"}
user {id: 456, tag:"tag1"}
给出用户ID,我想查找该用户是否具有所有3个标记(AND操作数)的记录. 如果用户具有"tag1"和"Tag2"和"tag3"的记录,则返回true
Given user id I want to find if this user has records with all 3 tags (AND operand). If user has records for "tag1" AND "Tag2" AND "tag3" then return true
SQL等效项如下:
SELECT * FROM users WHERE
EXISTS (SELECT * FROM tags WHERE user_id = users.id AND name ='tag1') AND
EXISTS (SELECT * FROM tags WHERE user_id = users.id AND name ='tag2') AND
user_id=123
如何在MongoDB中表达类似的东西?
How can I express something simular in MongoDB?
推荐答案
由于MongoDB没有联接的概念,因此您需要通过减少对单个文档的输入来解决这个问题.
Because MongoDB does not have a concept of joins, you need to work across this by reducing your input to a single document.
如果您更改文档结构以便存储标签数组,如下所示:
If you change your document structure so that you are storing an array of tags, like the following:
{id: 123, tag:["tag1","tag2","tag3"]}
{id: 456, tag:["tag1"]}
您可以执行以下查询:
db.user.find({$and:[{tag:"tag1"},{tag:"tag2"},{tag:"tag3"}]})
如果需要,您可以编写一个map-reduce来发出一个userid标签数组,因此您可以对它进行上面的查询.
If needed, you could write a map-reduce to emit an array of tags for a userid, so you can do the above query on it.
编辑-包括一个简单的map-reduce
这是一个非常简单的map-reduce,用于将初始输入转换成对上面给出的find
查询有用的格式.
Here is a really simple map-reduce to get the initial input into a format that is useful for the find
query given above.
var map = function() {emit(this.id, {tag:[this.tag]});}
var reduce = function(key, values){
var result_array=[];
values.forEach(function(v1){
v1.tag.forEach(function(v2){
result_array.push(v2);
});
});
return {"tag":result_array};}
var op = db.user.mapReduce(map, reduce, {out:"mr_results"})
然后,您可以查询map-reduce输出集合,如下所示:
Then you can query on the map-reduce output collection, like the following:
db.mr_results.find({$and:[{"value.tag":"tag1"},{"value.tag":"tag2"}, {"value.tag":"tag3"}]})
这篇关于将条件应用于MongoDB中同一字段的多个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!