我在mongodb有这个集合:
db.persons.find().pretty();{
"_id" : ObjectId("564635a944ae32e021f8b81b"),
"items" : [
{
"_id" : ObjectId("564635a944ae32e021f8b819"),
"personId" : 1,
"first_name" : "A",
"last_name" : "B",
"gender" : "m",
"comment" : "123"
},
{
"_id" : ObjectId("564635a944ae32e021f8b81a"),
"personId" : 2,
"first_name" : "w",
"last_name" : "X",
"gender" : "m",
"comment" : "987"
}
]},{
"_id" : ObjectId("564635a944ae32e021f8b812"),
"items" : [
{
"_id" : ObjectId("564635a944ae32e021f8b8d5"),
"personId" : 3,
"first_name" : "Y",
"last_name" : "Z",
"gender" : "f",
"comment" : "357"
}]}
使用此命令(findOne):
> db.persons.findOne({"items.personId" : 1})
得到这个结果:
{
"_id" : ObjectId("564635a944ae32e021f8b81b"),
"items" : [
{
"_id" : ObjectId("564635a944ae32e021f8b819"),
"personId" : 1,
"first_name" : "A",
"last_name" : "B",
"gender" : "m",
"comment" : "123"
},
{
"_id" : ObjectId("564635a944ae32e021f8b81a"),
"personId" : 2,
"first_name" : "w",
"last_name" : "X",
"gender" : "m",
"comment" : "987"
}
]}
但;我如何得到这个结果:只有first_name& last_name& _id来自personId = 1的项目
{
"_id" : ObjectId("564635a944ae32e021f8b819"),
"first_name" : "A",
"last_name" : "B"
}
(仅使用findOne命令(无聚合))。非常感谢...
答案 0 :(得分:2)
最好在投影中使用 positional $
运算符的组合来返回items数组,使用原生JavaScript的 map()
方法自定义为它返回的返回项数组只有你想要的字段然后因为只返回一个数组元素,你的最终结果是由0索引位置获得的。以下查询解释了上述内容:
var item = db.persons.findOne({"items.personId": 1}, {"items.$": 1, "_id": 0}).items.map(function (item){
return {
_id: item._id,
first_name: item.first_name,
last_name: item.last_name
}
})[0];
printjson(item);
输出:
{
"_id" : ObjectId("564635a944ae32e021f8b819"),
"first_name" : "A",
"last_name" : "B"
}
答案 1 :(得分:1)
看看:MongoDB get SubDocument。 简而言之:你想要什么似乎是不可能的。你会得到类似于aggergation的东西。 没有聚合你可以做的最好的事情是:
db.persons.findOne({"items.personId" : 1}, {"items.$", "_id":0})
会返回
{
"items" : [
{
"_id" : ObjectId("564635a944ae32e021f8b819"),
"first_name" : "A",
"last_name" : "B"
}
]
}