![](/img/trans.png)
[英]Mongoose - How do I find a specific document by matching an element in an array of object Ids in mongoose
[英]Mongoose - How do i find in a collection from an array of object ids
假設我有一個關於對象 ID 的數組:
[ 1, 2, 3, 4, 5 ]
我有一個名為 user 的集合,其中包含此值:
[
{
_id: 3,
name: 'hehe'
},
{
_id: 5,
name: 'hehe1'
},
{
_id: 2,
name: 'hehe2'
},
{
_id: 1,
name: 'hehe3'
},
{
_id: 4,
name: 'hehe4'
},
{
_id: 6,
name: 'hehe5'
}
]
我如何查詢數組對象 ID 到集合“用戶”? 結果應該與對象ID數組的順序相同,這可能嗎?
提前致謝!
您可以使用$in來過濾文檔,然后您可以使用$indexOfArray添加可以用作$sort鍵的特殊字段:
db.collection.aggregate([
{
$match: { _id: { $in: [ 1, 2, 3, 4, 5 ] } }
},
{
$addFields: { idx: { $indexOfArray: [ [ 1, 2, 3, 4, 5 ], "$_id" ] } }
},
{
$sort: { idx: 1 }
}
])
要獲取 Id 數組的文檔,您可以使用$in
如下
collection.find( { key: { $in: [array] }}, callback );
筆記:
不推薦使用文檔的順序來做一些邏輯。 我們不能指望訂單一直都一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.