Mongo: 是否可以在两个文档上满足 "and" 条件
Mongo: is it possible to satisfy "and" condition on two documents
假设我有两个文件
/*1*/
{
"id":1,
"name":"natty",
"subject_enrolled":"english"
}
/*2*/
{
"id":2,
"name":"natty",
"subject_enrolled":"science"
}
理想情况下,它应该是同一文档,subject_enrolled 是一个包含两个主题的数组。但出于某种原因,我保持我的数据像这样平坦。
现在,我想编写一个查询来检索所有已注册 "english" 和 "science" 的学生。
我尝试了以下查询:
db.students.find({"subject_enrolled":{"$in":["science", "english"]}})
但这是错误的,因为如果任何只注册科学的学生也会出现在结果中。我不能使用“$all”,因为科学和英语都在两个不同的文档中。
有没有办法轻松有效地实现这一目标?
我现在能想到的就是使用聚合。
db.students.aggregate([{"$group":{"_id":"$name", "subject_enrolled":{"$addToSet":"$subject_enrolled"}}}, {"$match":{"subject_enrolled":{"$all":["english", "science"]}}}])
完全满足我的条件
但我只担心性能。如果我说 10,000 个文档,最坏的情况是所有文档都是针对个别学生的,并且查询参数也是单个值,那么我将毫无意义地进行聚合!
Mongo各位高手,请大家谈谈我的情况
假设我有两个文件
/*1*/
{
"id":1,
"name":"natty",
"subject_enrolled":"english"
}
/*2*/
{
"id":2,
"name":"natty",
"subject_enrolled":"science"
}
理想情况下,它应该是同一文档,subject_enrolled 是一个包含两个主题的数组。但出于某种原因,我保持我的数据像这样平坦。 现在,我想编写一个查询来检索所有已注册 "english" 和 "science" 的学生。
我尝试了以下查询:
db.students.find({"subject_enrolled":{"$in":["science", "english"]}})
但这是错误的,因为如果任何只注册科学的学生也会出现在结果中。我不能使用“$all”,因为科学和英语都在两个不同的文档中。
有没有办法轻松有效地实现这一目标?
我现在能想到的就是使用聚合。
db.students.aggregate([{"$group":{"_id":"$name", "subject_enrolled":{"$addToSet":"$subject_enrolled"}}}, {"$match":{"subject_enrolled":{"$all":["english", "science"]}}}])
完全满足我的条件
但我只担心性能。如果我说 10,000 个文档,最坏的情况是所有文档都是针对个别学生的,并且查询参数也是单个值,那么我将毫无意义地进行聚合!
Mongo各位高手,请大家谈谈我的情况