在MongoDB中查询数组

问题描述 投票:0回答:1

我在MongoDB中有此集合:

{ 
    "_id" : ObjectId("5df013b10a88910018267a89"), 
    "StockNo" : "33598", 
    "Description" : "some description", 
    "detections" : [
        {
            "lastDetectedOn" : ISODate("2020-01-29T04:36:41.191+0000"), 
            "lastDetectedBy" : "comp-t", 
            "_id" : ObjectId("5e3135f68c9e930017de8aec")
        }, 
        {
            "lastDetectedOn" : ISODate("2019-12-21T18:12:06.571+0000"), 
            "lastDetectedBy" : "comp-n", 
            "_id" : ObjectId("5e3135f68c9e930017de8ae9")
        }, 
        {
            "lastDetectedOn" : ISODate("2020-01-29T07:36:06.910+0000"), 
            "lastDetectedBy" : "comp-a", 
            "_id" : ObjectId("5e3135f68c9e930017de8ae7")
        }
    ], 
    "createdAt" : ISODate("2019-12-10T21:52:49.788+0000"), 
    "updatedAt" : ISODate("2020-01-29T07:36:22.950+0000"), 
    "__v" : NumberInt(0)
}

我想通过StockNo搜索并获得最后一次检测到它的计算机的名称(lastDetectedBy),仅当lastDetectedOn是最近5分钟内与Express.node.js中的Mongoose一起使用时。

我也有这个收藏:

{ 
    "_id" : ObjectId("5df113b10d35670018267a89"), 
    "InvoiceNo" : "1", 
    "InvoiceDate" : ISODate("2020-01-14T02:18:11.196+0000"),
    "InvoiceContact : "",
    "isActive" : true
},
{ 
    "_id" : ObjectId("5df013c90a88910018267a8a"), 
    "InvoiceNo" : "2", 
    "InvoiceDate" : ISODate("2020-01-14T02:18:44.279+0000"),
    "InvoiceContact : "Bob Smith",
    "isActive" : true
},
{ 
    "_id" : ObjectId("5e3096bb8c9e930017dc6e20"), 
    "InvoiceNo" : "3", 
    "InvoiceDate" : ISODate("2020-01-14T02:19:50.155+0000"),
    "InvoiceContact : "",
    "isActive" : true
}

并且我想用过去30秒钟(或者从现在到过去的某个时间范围内的任何日期范围)发出的空InvoiceContact更新所有文档,其中isActive等于true,isActive等于false。因此,例如,第一条记录是在最近30秒内发布的,而没有InvoiceContact,并且isActive为true,因此必须对其进行更新,但是由于不同的原因,接下来的两条记录将保持不变,第二条记录具有InvoiceContact,而第三条记录将不存在范围。

node.js mongodb express
1个回答
0
投票

第一部分

 var mins5 = new Date(ISODate() - 1000* 60 * 5 )

 db.getCollection('user').find({$and:[
     { "StockNo":"33598"},
     {"detections.lastDetectedOn" : { $gte : mins5 }}
     ]})
     .map(function(list){
         var results = [];
         list.detections.forEach(function (detections){
             if(detections.lastDetectedOn > mins5){
                 results.push(detections.lastDetectedBy);
             }
         })
         return results;
     });

第二部分可以通过使用update而不是find的类似查询来解决。

© www.soinside.com 2019 - 2024. All rights reserved.