我是mongo的新手,我试图通过子文档中的值获取组,并使用mongo集合结构:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 29
at java.lang.String.charAt(String.java:686)
at EncryptDecrypt.encrypt(EncryptDecrypt.java:14)
at EncryptDecrypt.main(EncryptDecrypt.java:28)
在这里,我想在此进行分组。 例如在mysql中:
{
"_id" : ObjectId("589d4e4b270f8b1635d400b1"),
"myShopId" : 439,
"products" : [
{
"productId" : "1234",
"productName" : "sambarpowder 500 gm",
"productCategory" : "masala",
"mrp" : "90",
"_id" : ObjectId("589d595f6da20b72fe006ea9")
},
{
"productId" : "5678",
"productName" : "moong dhal 200 gms",
"productCategory" : "dhal",
"mrp" : "38 ",
"_id" : ObjectId("589d595f6da20b72fe006eaa")
},
{
"productId" : "5678",
"productName" : "moong dhal 200 gms",
"productCategory" : "dhal",
"mrp" : "38 ",
"_id" : ObjectId("589d595f6da20b72fe006eaa")
}
],
"isAlive" : 1,
"__v" : 3
}
如何在mongo子文档中实现该组
select productCategory from products where shopId = '439' groupby productCategory
答案 0 :(得分:4)
希望这会有所帮助,
db.test.aggregate([{
$match: {
myShopId: 439
}
}, {
$unwind: "$products"
}, {
$group: {
_id: {
"productCategory": "$products.productCategory"
},
"id": {
$first: "$products._id"
}
}
}])
输出:
{" _id" :{" productCategory" :" dhal" }," id" :ObjectId(" 589d595f6da20b72fe006eaa")}
{" _id" :{" productCategory" :" masala" }," id" :ObjectId(" 589d595f6da20b72fe006ea9")}