嵌套数组MongoDB中的查询对象

时间:2018-10-20 20:13:16

标签: python mongodb pymongo

已被标记为重复。但是,标记为重复的答案是我已经查看过的答案,但并没有帮助我。请继续阅读。

在MongoDB中,我试图从嵌套数据集中返回过滤后的结果。我已经在这里尝试过解决以前回答过的问题的方法,但是到目前为止,没有一个对我有用。

这是我的数据示例,其中的数组“酒精”中包含一个对象(带有第二个嵌套对象“食谱”)。实际数据在“酒精”数组中有多个对象,所有对象的字段均相同,但值不同。为了节省空间,我没有在此处包括所有内容。

`{
  "_id": {
    "$oid": "5bc53e0ce7179a4377fb226e"
  },
  "category": {
    "alcohol": [
      {
        "cat_name": "beer",
        "recipe_name": "summer lager",
        "style": "lager",
        "level": "intermediate",
        "flavour": "sweet",
        "region": "n.american",
        "method": "top-fermented",
        "properties": "ABV 4%",
        "free-from": [
          "gluten-free"
        ],
        "recipe": {
          "recipe_name": "summer lager",
          "description": "sparkling, light & fresh",
          "equip_list": [
            "scissors",
            "saucepan",
            "strainer"
          ],
          "ingredients_list": [
            "10 cups water",
            "300g southern dry hops",
            "25g beer yeast"
          ],
          "prep_method": [
            "pour the water into an airtight container",
            "add the yeast",
            "roast the hops gently",
            "remove from the heat",
            "leave to steep for 30 minutes",
            "close the airlock, and keep checking"
          ],
          "added_by": "allie smyth",
          "date_added": "02/10/17",
          "upvotes": "25",
          "url": "/"
        }
      }
    ]
  }
}`

想象一下,“酒精”数组中有多个对象,假设我只想检索上述对象。通过阅读文档,我认为语法如下:

    db.find({"category.alcohol": {"$elemMatch": {"recipe_name":"summer lager"}}})  

但是,这将继续返回整个集合。我也尝试过使用$ in修饰符,如下所示,但这不会返回任何内容:

    db.find({"category.alcohol": {"$in": ["summer lager", "intermediate"]}})

我能够限制查询结果的最接近方法是使用投影运算符返回找到的第一个包含给定值的对象。

    db.find({"category.alcohol.recipe_name":"summer lager"}, {"_id":0, "category.alcohol.$":1})

但是,对我来说这没什么用,因为我希望能够返回所有符合查询参数的对象。

如果需要提供更多信息,请告诉我。这是我使用该论坛的第一篇文章。谢谢:)

0 个答案:

没有答案
相关问题