如何通过查询 MongoDB 中的子文档将数组用作过滤器?
要进行此操作,请在 MongoDB 中使用 $setIsSubset。让我们创建一个包含文档的集合 -
> db.demo407.insertOne(
... {
... Name:"Chris",
... "details" : [
... {
... id:100
... },
... {
... id:110
... },
... {
... id:130
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e70dffe15dc524f70227677")
}在集合中显示所有文档,方法是使用 find() 方法 -
> db.demo407.find().pretty();
将产生以下输出 -
{
"_id" : ObjectId("5e70dffe15dc524f70227677"),
"Name" : "Chris",
"details" : [
{
"id" : 100
},
{
"id" : 110
},
{
"id" : 130
}
]以下是通过查询子文档将数组用作过滤器的查询 -
> db.demo407.aggregate([
... {$match: { }},
... {$project: {
... "details": {
... $filter: {
... input: "$details",
... as: "output",
... cond: { $setIsSubset: [["$$output.id"],[100, 130]] }
... }
... }
... }}])将产生以下输出 -
{ "_id" : ObjectId("5e70dffe15dc524f70227677"), "details" : [ { "id"
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP