[英]Is there any way to pass array of indexes to mongodb and get elements from array at that indexes
我有一個包含 100 個元素的數組的 mongodb 文檔,我想在查詢數組中給定的索引處從該數組中獲取多個元素。 示例:讓查詢 = [2,3,5,6,7,4,44,32,71]; 所以,我想在查詢數組中給出的索引處獲取 mongodb doc 中數組中的元素。
如果你想在 mongo 端過濾數據,你可以這樣做。
db.getCollection('feed').find({
"_id" : {
"$in" : [
ObjectId("55880c251df42d0466919268"),
ObjectId("55bf528e69b70ae79be35006")
]
}
});
如果不,
const filteredResult = items.filter(item => query.includes(item._id));
console.log(filteredResult);
沒有內置的 mongodb 運算符可以開箱即用地支持您的要求,但是......您可以通過非常難以閱讀的聚合管道來實現它,如下所示:
var query = [1, 3, 5]
db.Collection.aggregate(
[
{
$match: { "_id": ObjectId("5fd33ddd23505e1538b96116") }
},
{
$set: {
Array: {
$map: {
input: {
$filter: {
input: {
$map: {
input: "$Array",
as: "x",
in: {
Position: { $add: [{ $indexOfArray: ["$Array", "$$x"] }, 1] },
Value: "$$x"
}
}
},
as: "xx",
cond: { $in: ["$$xx.Position", query] }
}
},
as: "xxx",
in: "$$xxx.Value"
}
}
}
}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.