我有一些看起来像这样的数据:
{
"_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());
感谢任何帮助。
最佳答案
可以在js代码中嵌入索引 你需要这样的东西。
function count(myguid, index) {
const query = {"guid": myguid};
query["v." + index + ".cnt"] = {$exists: true};
return db.MuCollection.count(query);
}
此方法将生成针对特定索引和计数对象的查询
用法
count("some-guid", 3);
关于javascript - MongoDB 查询以计算存在特定数组索引的文档。索引在 javascript 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43402129/