2017-10-04 120 views
0

我想獲得前X項和y項後(的鄰居)與"lastseen":true記錄:如何獲取特定物品周圍的物品?

// (_id fields omitted) 
{ "msg": "hello 1" } 
{ "msg": "hello 2" } 
{ "msg": "hello 3", "lastseen": true } 
{ "msg": "hello 4" } 
{ "msg": "hello 5" } 

例如,如果我有x=1y=1查詢結果應該是:

// (_id fields omitted) 
{ "msg": "hello 2" } 
{ "msg": "hello 3", "lastseen": true } 
{ "msg": "hello 4" } 

在mongodb中我可以實現的選項有哪些?

+0

這些單個文檔或子文檔是否在文檔中? –

+0

個人,沒有子/嵌入文檔 – Fabricio

回答

0

答案是很短的,你可以用略()跳過你想要多少 //(略_id字段)

{ 「味精」: 「你好1」}

{ 「味精」 : 「你好2」}`

{ 「msg」 中: 「你好3」, 「lastseen」:真}

{ 「msg」 中: 「你好4」} { 「msg」 中:「你好5「}

命令:
db.collection.find({},{_ ID:0})。跳過(1)

+0

如果我的答案幫助標記爲答案 – Mahesh

1

它必須是比較簡單與多個查詢來實現客戶端上的邏輯。假設你的文件被_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"}} 
]); 

但我懷疑這種查詢的效率。

相關問題