MongoDB-查询嵌入式文档

时间:2020-02-23 14:40:52  来源:igfitidea点击:

在此MongoDB教程中,我们将学习查询嵌入式文档。

在上一教程中,我们了解了如何查询文档,逻辑运算符以及如何选择特定字段。

嵌入或者嵌套的文档

对于本教程,让我们继续创建一些嵌入式文档。
因此,连接到您的MongoDB服务器并运行以下命令以在shapes集合中插入一些文档。

> db.shapes.insertMany([
  {
    "shape": "rectangle",
    "item": "Rect 1",
    "dim": {
      "length": 10,
      "breadth": 20,
      "uom": "cm"
    }
  },
  {
    "shape": "rectangle",
    "item": "Rect 2",
    "dim": {
      "length": 20,
      "breadth": 30,
      "uom": "cm"
    }
  },
  {
    "shape": "rectangle",
    "item": "Rect 3",
    "dim": {
      "length": 5,
      "breadth": 10,
      "uom": "cm"
    }
  },
  {
    "shape": "square",
    "item": "Sq 1",
    "dim": {
      "side": 10.5,
      "uom": "cm"
    }
  },
  {
    "shape": "square",
    "item": "Sq 2",
    "dim": {
      "side": 20,
      "uom": "cm"
    }
  },
  {
    "shape": "square",
    "item": "Sq 3",
    "dim": {
      "side": 15,
      "uom": "inch"
    }
  },
  {
    "shape": "square",
    "item": "Sq 4",
    "dim": {
      "side": 25.5,
      "uom": "inch"
    }
  }
]);

我们在"插入文档"教程中学习了如何创建嵌入式文档。
随时检查一下。

好吧,让我们从简单开始,然后逐步解决问题。

查找所有矩形

要在" shapes"集合中找到代表矩形的所有文档,我们必须运行以下命令。

> db.shapes.find({ "shape": "rectangle" }).pretty();

{
  "_id" : ObjectId("5d175dffba3250e57f98faca"),
  "shape" : "rectangle",
  "item" : "Rect 1",
  "dim" : {
    "length" : 10,
    "breadth" : 20,
    "uom" : "cm"
  }
}
{
  "_id" : ObjectId("5d175dffba3250e57f98facb"),
  "shape" : "rectangle",
  "item" : "Rect 2",
  "dim" : {
    "length" : 20,
    "breadth" : 30,
    "uom" : "cm"
  }
}
{
  "_id" : ObjectId("5d175dffba3250e57f98facc"),
  "shape" : "rectangle",
  "item" : "Rect 3",
  "dim" : {
    "length" : 5,
    "breadth" : 10,
    "uom" : "cm"
  }
}

查找边长至少20厘米的正方形

好了,我们现在正在转向嵌入式文档。

首先,我们必须检查"形状"是否等于"正方形"。

接下来,我们必须检查" dim"字段内的" side"字段。
因此,我们必须在过滤器中使用dim.side

我们必须确保侧面至少20厘米,因此我们必须对dim.side字段使用大于或者等于运算符的$gte。

对于测量单位" uom",我们必须检查" dim.uom"是否等于" cm"。

我们的查询应如下所示。

> db.shapes.find({
  "shape": "square",
  "dim.side": { $gte: 20 },
  "dim.uom": "cm"
}).pretty();

{
  "_id" : ObjectId("5d175dffba3250e57f98face"),
  "shape" : "square",
  "item" : "Sq 2",
  "dim" : {
    "side" : 20,
    "uom" : "cm"
  }
}

查找所有长度至少为10厘米,宽度至少为20厘米的矩形

为此,我们必须检查以下内容。

  • 形状是矩形
  • dim.length至少(即大于或者等于)10
  • dim.breadth至少(即大于或者等于)20
  • 厘米
> db.shapes.find({
  "shape": "rectangle",
  "dim.length": { $gte: 10 },
  "dim.breadth": { $gte: 20 },
  "dim.uom": "cm"
}).pretty();

{
  "_id" : ObjectId("5d175dffba3250e57f98faca"),
  "shape" : "rectangle",
  "item" : "Rect 1",
  "dim" : {
    "length" : 10,
    "breadth" : 20,
    "uom" : "cm"
  }
}
{
  "_id" : ObjectId("5d175dffba3250e57f98facb"),
  "shape" : "rectangle",
  "item" : "Rect 2",
  "dim" : {
    "length" : 20,
    "breadth" : 30,
    "uom" : "cm"
  }
}