如何从Mongodb中数组中的文档投影特定字段?
要从数组中的文档投影特定字段,可以使用位置($)运算符。
首先让我们创建一个包含文档的集合
> db.projectSpecificFieldDemo.insertOne(
... {
... "UniqueId": 101,
... "StudentDetails" : [{"StudentName" : "Chris", "StudentCountryName ": "US"},
... {"StudentName" : "Robert", "StudentCountryName" : "UK"},
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca27aeb6304881c5ce84ba2")
}
> db.projectSpecificFieldDemo.insertOne( { "UniqueId": 102, "StudentDetails" :
[{"StudentName" : "Robert", "StudentCountryName ": "UK"}, {"StudentName" : "David",
"StudentCountryName" : "AUS"}, ] } );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca27b106304881c5ce84ba3")
}以下是在find()方法的帮助下显示集合中所有文档的查询
> db.projectSpecificFieldDemo.find().pretty();
这将产生以下输出
{
"_id" : ObjectId("5ca27aeb6304881c5ce84ba2"),
"UniqueId" : 101,
"StudentDetails" : [
{
"StudentName" : "Chris",
"StudentCountryName " : "US"
},
{
"StudentName" : "Robert",
"StudentCountryName" : "UK"
}
]
}
{
"_id" : ObjectId("5ca27b106304881c5ce84ba3"),
"UniqueId" : 102,
"StudentDetails" : [
{
"StudentName" : "Robert",
"StudentCountryName " : "UK"
},
{
"StudentName" : "David",
"StudentCountryName" : "AUS"
}
]
}以下是查询以从数组内的文档投影特定字段的查询
> var myDocument = { UniqueId : 101, 'StudentDetails.StudentName' : 'Chris' };
> var myProjection= {'StudentDetails.$': 1 };
> db.projectSpecificFieldDemo.find(myDocument , myProjection).pretty();这将产生以下输出
{
"_id" : ObjectId("5ca27aeb6304881c5ce84ba2"),
"StudentDetails" : [
{
"StudentName" : "Chris",
"StudentCountryName " : "US"
}
]
}热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短