MongoDB 查询数组元素不具有特定值的文档
对于此类情况,请使用 $elemMatch。此运算符匹配包含数组字段的文档,其中至少一个元素与所有指定查询条件相匹配。
让我们创建一个包含文档的集合 −
> db.demo239.insertOne(
... {
... "Name" : "Chris",
... "details" : [
... { "DueDate" : new ISODate("2019-01-21"), "ProductPrice" : 1270 },
... { "DueDate" : new ISODate("2020-02-12"), "ProductPrice" : 2000 }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e441c6bf4cebbeaebec5157")
}
> db.demo239.insertOne(
... {
... "Name" : "David",
... "details" : [
... { "DueDate" : new ISODate("2018-11-11"), "ProductPrice" : 1450},
... { "DueDate" : new ISODate("2020-02-12") }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e441c6cf4cebbeaebec5158")
}在集合中使用 find() 方法显示所有文档 −
> db.demo239.find();
这将产生以下输出 −
{
"_id" : ObjectId("5e441c6bf4cebbeaebec5157"), "Name" : "Chris", "details" : [
{ "DueDate" : ISODate("2019-01-21T00:00:00Z"), "ProductPrice" : 1270 },
{ "DueDate" : ISODate("2020-02-12T00:00:00Z"), "ProductPrice" : 2000 }
]
}
{
"_id" : ObjectId("5e441c6cf4cebbeaebec5158"), "Name" : "David", "details" : [
{ "DueDate" : ISODate("2018-11-11T00:00:00Z"), "ProductPrice" : 1450 },
{ "DueDate" : ISODate("2020-02-12T00:00:00Z") }
]
}以下是用于获取其数组元素不具有特定值的文档的查询 −
> db.demo239.find({ "details": { "$elemMatch": { "DueDate": { "$exists": true }, "ProductPrice": { "$exists": false } } } })这将产生以下输出 −
{ "_id" : ObjectId("5e441c6cf4cebbeaebec5158"), "Name" : "David", "details" : [ { "DueDate" : ISODate("2018-11-11T00:00:00Z"), "ProductPrice" : 1450 }, { "DueDate" : ISODate("2020-02-12T00:00:00Z") } ] }
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP