它必須是比較簡單與多個查詢來實現客戶端上的邏輯。假設你的文件被_id下令:
findOne({"lastseen":true})
find({_id: {$lt: <_id from the previous query>}}).sort({_id:-1}).limit(1)
find({_id: {$gt: <_id from the first query>}}).sort({_id:1}).limit(1)
做在單個查詢我能想象的唯一方法是,把文件轉換成數組,然後結合使用$indexOfArray和$slice:
db.collection.aggregate([
// ensure lastseen is present to calculate index properly
{ $addFields: {lastseen: { $ifNull: [ "$lastseen", false ] } } },
// get all documents into array
{ $group: { _id:null, docs: { $push:"$$ROOT" } } },
// get index of first matched document
{ $project: { docs:1, match: { $indexOfArray: [ "$docs.lastseen", true ] } } },
// slice the array
{ $project: { docs: { $slice: [ "$docs", { $subtract: [ "$match", 1 ] } , 3 ] } } },
// remove added lastseen
{ $project: { docs:
{ $map: {
input: "$docs",
as: "doc",
in: { $cond: {
if: "$$doc.lastseen",
then: "$$doc",
else: { $arrayToObject: { $filter: {
input: { $objectToArray: "$$doc" },
as: "field",
cond: { $ne: [ "$$field.k", "lastseen" ] }
} } }
} }
} }
} },
// un-group documents from the array
{ $unwind: "$docs" },
{ $replaceRoot: {newRoot:"$docs"}}
]);
但我懷疑這種查詢的效率。
這些單個文檔或子文檔是否在文檔中? –
個人,沒有子/嵌入文檔 – Fabricio