如何解决具有投影的MongoDB查询没有嵌套字段且没有固定的父名称
我正在尝试通过使用投影的查询从MongoDB中检索一些文档。
文档看起来像这样:
{
"_id": "01","country": "EUA","created": "2020-09-10T18:12:20.649Z","products": {
"0001": {
"id": "0001","price": "1.25","timestamp": "16004443546","class": "com.website.ecommerce.src.main.java.model.product"
},"0123": {
"id": "0123","price": "1.50","0443": {
"id": "00443","price": "1.75","class": "com.website.ecommerce.src.main.java.model.product"
}
}
}
我不需要检索“ class”字段,因此在查询结果超过10k的情况下,该字段代表了响应大小的很大一部分。
collection.find({'_id': some_id},{'products.*._class': 0 })
我的猜测是有某种通配符可以胜任,但我找不到。
我尝试过:,$,$ ,$ **,** 但没有成功。
解决方法
//actual code output from mongoshell 4.2.6 on windows
//prepare the document in a collection called eua,as given in problem statement
> db.eua.find().pretty();
{
"_id" : "01","country" : "EUA","created" : "2020-09-10T18:12:20.649Z","products" : {
"0001" : {
"id" : "0001","price" : "1.25","timestamp" : "16004443546","class" : "com.website.ecommerce.src.main.java.model.product"
},"0123" : {
"id" : "0123","price" : "1.50","0443" : {
"id" : "00443","price" : "1.75","class" : "com.website.ecommerce.src.main.java.model.product"
}
}
}
//use aggreate project command to first convert object to array in first stage
// use the project in 2nd stage to hide the class field
// reconvert back to original array to object with required fields marked as 1
> db.eua.aggregate([
...
... {
... $project: {
... _id: 1,... country: 1,... created: 1,... prodToArray: {
... $objectToArray: "$products"
... }
... }
... },... {
... $project: {
... "prodToArray.v.class": 0
... }
... },... {
... $project:{
... _id: 1,... country: 1,... created: 1,... products:{
... $arrayToObject:"$prodToArray"
... }
... }
... }
... ]).pretty()
{
"_id" : "01","timestamp" : "16004443546"
},"timestamp" : "16004443546"
}
}
}
>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。