如何从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"
}
]
}热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练