2017-04-13 45 views
1

我有一些數據,看起來像這樣:MongoDB查詢來計數文件a特定數組索引的存在位置。指數是在JavaScript變量

{ 
"_id" : ObjectId("58efcbb9ac808c5c0771b1b0"), 
"guid" : "cda474b9-1362-4ffe-99df-5c0783fff8be", 
"g" : "SomeString", 
"m" : "Something else", 
"r" : null, 
"dh" : ISODate("2017-04-13T19:00:00.000Z"), 
"ei" : 60000, 
"v" : [ 
    {}, 
    {}, 
    {}, 
    {}, 
    { 
     "last" : 0.0, 
     "sum" : 0.0, 
     "cnt" : 1, 
     "minimum" : 0.0, 
     "maximum" : 0.0 
    }, 
    {}, 
    {} 
] 

}

有這樣的許多文件。對於單個GUID,可能會有100個文件,如上面的文件。我想要做的是計算guid = SOMEGUID和元素「cnt」存在於特定數組元素的文檔數量。

捕捉的是,數組元素索引存儲在一個變量中。它來自其他地方。

這條線:

print(myguid + ": " + db.MyCollection.find({"guid" : myguid, "v.4.cnt" : { $exists : true}}).count()); 

以上的偉大工程。它輸出是這樣的:

2e605c07-54b2-49e6-8a9f-f31d3dffe57c: 28 

我的問題是,我不想用「4」,我有存儲在一個名爲arrayIndex變量的指標,我想嵌入在查詢中。

這樣的查詢不起作用:

print(myguid + ": " + db.MyCollection.find({"guid" : myguid, "v.arrayIndex.cnt" : { $exists : true}}).count()); 

任何幫助表示讚賞。

回答

2

你可以在js代碼中嵌入索引 你需要類似這樣的東西。

function count(myguid, index) { 
    const query = {"guid": myguid}; 
    query["v." + index + ".cnt"] = {$exists: true}; 

    return db.MuCollection.count(query); 
} 

這種方法會產生特定的指數和計數查詢對象

使用

count("some-guid", 3); 
+0

這是正是我需要的。謝謝! – BillK

+0

或者只是'db.MyCollection.find({guid:myguid,\ v。$ {arrayIndex} .cnt \':{$ exists:true}})。count()' – Guig

+0

@Guig。我認爲這不適用於老版本的mongodb – Gor