![](/img/trans.png)
[英]Given an array of matches, find all documents that have atleast one match and replace all matches with given value
[英]How can you find all documents that match the last element of an array field with a given query value in Mongoose?
我有一個結構類似於的集合:
type Products {
productid: String
owners: [String]
}
在我的查詢中,我輸入了一個值user
。 我需要檢索與owners
最后一個元素匹配的所有文檔,希望使用 find。 我試過Products.find({ "$owners.-1": user })
到目前為止沒有運氣
有沒有辦法訪問這個數組的最后一個元素?
如果您只想獲取傳入的user
值是Products
集合中owners
數組中最后一個元素的文檔,請嘗試以下操作:
var user = 'myname';
Products.find( { $expr: {$eq : [{ $arrayElemAt: [ '$owners', -1 ] }, user]} })
收集數據:
/* 1 */
{
"_id" : ObjectId("5e1f82b0d02e05b694b48b9d"),
"productid" : "1",
"owners" : [
"others",
"myname"
]
}
/* 2 */
{
"_id" : ObjectId("5e1f84d3d02e05b694b4cbe0"),
"productid" : "2",
"owners" : [
"others",
"myname",
"anothername"
]
}
/* 3 */
{
"_id" : ObjectId("5e1f84e2d02e05b694b4cee2"),
"productid" : "3",
"owners" : [
"myname",
"anothername"
]
}
/* 4 */
{
"_id" : ObjectId("5e1f84ebd02e05b694b4d0d0"),
"productid" : "4",
"owners" : [
"myname"
]
}
結果 :
/** Only "productid" : "1" & "productid" : "4" are returned */
/* 1 */
{
"_id" : ObjectId("5e1f82b0d02e05b694b48b9d"),
"productid" : "1",
"owners" : [
"others",
"myname"
]
}
/* 2 */
{
"_id" : ObjectId("5e1f84ebd02e05b694b4d0d0"),
"productid" : "4",
"owners" : [
"myname"
]
}
下面將為您提供所有者列表中的最后一個元素。
db.Products.find( {}, { owners: { $slice: -1 } } );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.