如何从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 婆婆高寿祝福语大全简短