通过MongoDB中的投影从嵌套文档中删除除单个字段以外的所有字段
将您不想包含的字段设置为0。使用时,该字段将显示其余值find()。首先让我们创建一个包含文档的集合-
> db.demo237.insertOne({
... _id:101,
... Product: {
... description1: {id:1001 },
... description2: {Name:"Product-1" },
... description3: {Price:550 }
... }
...}
...);
{ "acknowledged" : true, "insertedId" : 101 }在find()方法的帮助下显示集合中的所有文档-
> db.demo237.find().pretty();
这将产生以下输出-
{
"_id" : 101,
"Product" : {
"description1" : {
"id" : 1001
},
"description2" : {
"Name" : "Product-1"
},
"description3" : {
"Price" : 550
}
}
}以下是通过投影从嵌套文档中删除除单个字段以外的所有字段的查询-
> db.demo237.find({}, { "Product.description1": 0, "Product.description3": 0 });这将产生以下输出-
{ "_id" : 101, "Product" : { "description2" : { "Name" : "Product-1" } } }