MongoDB-查询数组

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

在本MongoDB教程中,我们将学习查询数组。

登录到您的MongoDB服务器并插入以下文档。

对于本教程,我会将以下文档插入posts集合中。

> db.posts.insertMany([
  {
    "title": "This is my first post!",
    "tags": ["awesome", "post", "blog"]
  },
  {
    "title": "Dinner time :)",
    "tags": ["food", "dinner", "fun"]
  },
  {
    "title": "Birthday Treat",
    "tags": ["fun", "food", "birthday", "treat", "party"]
  }
]);

匹配精确数组

在下面的示例中,我们将获取数组中恰好有3个元素的文档,其值依次为" awesome"," post"和" blog"。

> db.posts.find({
  "tags": ["awesome", "post", "blog"]
}).pretty();

{
  "_id" : ObjectId("5d1b43d9085e37060f4c36b5"),
  "title" : "This is my first post!",
  "tags" : [
    "awesome",
    "post",
    "blog"
  ]
}

注意!如果在上面的查询中更改数组元素的位置,则将不会得到相同的结果。

查询数组中的元素

在下面的示例中,我们将获取所有包含标签字段" tags"的文档,其中包含" food"作为数组元素之一。

> db.posts.find({ "tags": "food" }).pretty();

{
  "_id" : ObjectId("5d1b43d9085e37060f4c36b6"),
  "title" : "Dinner time :)",
  "tags" : [
    "food",
    "dinner",
    "fun"
  ]
}
{
  "_id" : ObjectId("5d1b43d9085e37060f4c36b7"),
  "title" : "Birthday Treat",
  "tags" : [
    "fun",
    "food",
    "birthday",
    "treat",
    "party"
  ]
}

查询数组中的某些元素

在下面的示例中,我们将以任意顺序从值列表中获取所有具有数组字段tags的文档,这些值包含值food,dinner和fun的列表。

读取标签数组中任何顺序具有"食物","乐趣"或者"晚餐"的任何文档。

> db.posts.find({
  tags: { $in: ["food", "fun", "dinner"] }
}).pretty();

{
  "_id" : ObjectId("5d1b43d9085e37060f4c36b6"),
  "title" : "Dinner time :)",
  "tags" : [
    "food",
    "dinner",
    "fun"
  ]
}
{
  "_id" : ObjectId("5d1b43d9085e37060f4c36b7"),
  "title" : "Birthday Treat",
  "tags" : [
    "fun",
    "food",
    "birthday",
    "treat",
    "party"
  ]
}

查询数组中给定元素的顺序不一

在下面的示例中,我们将获取所有具有数组字段tags的所有文档,其中tags具有任意顺序的值food,dinner和fun列表。

> db.posts.find({
  tags: { $all: ["food", "fun", "dinner"] }
}).pretty();

{
	"_id" : ObjectId("5d1b43d9085e37060f4c36b6"),
	"title" : "Dinner time :)",
	"tags" : [
		"food",
		"dinner",
		"fun"
	]
}

按数组长度查询

在下面的示例中,我们将获取所有具有3个元素的数组字段tags的文档。

> db.posts.find({
  "tags": { $size: 3 }
}).pretty();

{
  "_id" : ObjectId("5d1b43d9085e37060f4c36b5"),
  "title" : "This is my first post!",
  "tags" : [
    "awesome",
    "post",
    "blog"
  ]
}
{
  "_id" : ObjectId("5d1b43d9085e37060f4c36b6"),
  "title" : "Dinner time :)",
  "tags" : [
    "food",
    "dinner",
    "fun"
  ]
}