mongo搜索超过1个相同标准的集合

时间:2015-06-04 07:00:24

标签: mongodb

我有一个包含多个集合的mongo数据库,其中包含如下所示的JSON文档格式:

{
  "questions": [
    {
      "questionEntry": {
        "id": 1,
        "info": {
          "seasonNumber": 1,
          "episodeNumber": 1,
          "episodeName": "Days Gone Bye"
        },
        "questionItem": {
          "theQuestion": "q1",
          "attachedElement": {
            "type": 1,
            "value": ""
          }
        },
        "options": [
          {
            "type": 1,
            "value": "o1"
          },
          {
            "type": 1,
            "value": "o1"
          }
        ],
        "answer": {
          "questionId": 1,
          "answer": 1
        },
        "metaTags": [
          "Season 1",
          "Episode 1",
          "Rick Grimmes"
        ]
      }
    },
    {
      "questionEntry": {
        "id": 1,
        "info": {
          "seasonNumber": 1,
          "episodeNumber": 1,
          "episodeName": "Days Gone Bye"
        },
        "questionItem": {
          "theQuestion": "q2",
          "attachedElement": {
            "type": 1,
            "value": ""
          }
        },
        "options": [
          {
            "type": 1,
            "value": "o2"
          },
          {
            "type": 1,
            "value": "o2"
          }
        ],
        "answer": {
          "questionId": 1,
          "answer": 1
        },
        "metaTags": [
          "Season 1",
          "Episode 1",
          "Rick Grimmes",
          "Glenn Rhee"
        ]
      }
    }
  ]
}

我可以搜索问题.questionEntry.questionItem.theQuestion以获得匹配条件:

db.questions.find({"questions.questionEntry.questionItem.theQuestion" : "q1"},{'questions.$':1}).pretty()

这适用于问题集,但我如何在多个集合中进行相同的搜索?

非常感谢

2 个答案:

答案 0 :(得分:1)

要在多个集合中使用相同的查询,您可能必须使用JavaScript bracket notation 来循环访问集合。例如,以下使用指定查询查询use records var colls = db.getCollectionNames(), // get all the collections in records db query = {"questions.questionEntry.questionItem.theQuestion" : "q1"}, projection = {"questions.$": 1}; colls.forEach(function (collection){ var docs = db[collection].find(query, projection).toArray(); // use the bracket notation docs.forEach(function (doc){ printjson(doc); }); }) 数据库中所有集合(使用db.getCollectionNames()命令):

{{1}}

答案 1 :(得分:0)

你必须自己做。没有开箱即用的支持。

您可以查询MongoDB多线程(取决于您的编程语言)并将结果聚合为统一结果。