0
我有一個MongoDB的集合,被稱爲bios
,即含有類似這些文件:檢索數組的第二個元素爲每個文檔 - MongoDB的
{
"_id" : ObjectId("51df07b094c6acd67e492f41"),
"name" : {
"first" : "John",
"last" : "McCarthy"
},
"birth" : ISODate("1927-09-04T04:00:00Z"),
"death" : ISODate("2011-12-24T05:00:00Z"),
"contribs" : [
"Lisp",
"Artificial Intelligence",
"ALGOL"
]
},
{
"_id" : 3,
"name" : {
"first" : "Grace",
"last" : "Hopper"
},
"title" : "Rear Admiral",
"birth" : ISODate("1906-12-09T05:00:00Z"),
"death" : ISODate("1992-01-01T05:00:00Z"),
"contribs" : [
"UNIVAC",
"compiler",
"FLOW-MATIC",
"COBOL"
]
}
我的目標是檢索數組貢獻的第二個元素每個文件在bios
集合中。 使用新的聚合管道運營商$filter我運行下面的查詢:
> db.bios.aggregate([
{
$match: {"contribs.2":{"$exists":1}}},
{
$project:{contribs:
{
$filter:{input:"$contribs", as: "contribs", cond:{}}},_id:0}}])
隨着我的查詢,輸出是:
{ "contribs" : [ "Lisp", "Artificial Intelligence", "ALGOL" ] }
{ "contribs" : [ "UNIVAC", "compiler", "FLOW-MATIC", "COBOL" ] }
這不僅僅是陣列contribs
但投影的第二個元素當它的第二個元素存在時,在contribs
數組上。
使用'.aggregate()'在這裏可能是過量的。使用'db.bios.find({「contribs.1」:{「$ exists」:true}},{「contribs。$」:1})'將返回匹配的元素。返回的''contribs''仍然是一個數組,但它只會是一個單獨的元素,所以很容易在代碼中引用。 ['$ arrayElemAt'](https://docs.mongodb.org/manual/reference/operator/aggregation/arrayElemAt/)操作符將作爲單個值返回,但除非在結果之後繼續聚合管道,否則它不應該是必要的。也不是最高性能的方法。 –