简体   繁体   中英

MongoDB find subdocument

I am starting a collection for aggregated results. So I am following MO 'Pre aggegrated reports'

I am inserting docs with this schema:

{
"_id" : "20160526/78220/59",
"metadata" : {
    "date" : "2016-05-26",
    "offer" : "78220",
    "adv" : NumberLong(59),
    "update" : ISODate("2016-05-26T10:49:25.597Z")
},
"daily" : NumberLong(6),
"hourly" : {
    "12" : NumberLong(6)
},
"publisher" : {
    "43" : {
        "daily" : NumberLong(3),
        "hourly" : {
            "12" : NumberLong(3)
        }
    },
    "738" : {
        "daily" : NumberLong(3),
        "hourly" : {
            "12" : NumberLong(3)
        }
    }
}

The idea is to have aggregated info from every hour from every publisher. _id is date/offer/code, and every publisher can give some offers. But now I need to get, for example, a sum of the daily or hourly data for all publisher's offers.

My main question is how can I access a report on specific publisher, for example, 738, or 43? If I query:

db.getCollection('daily_aggregate').find({'publisher.738':{$exists:true}})

I get all documents that has publisher 738, but I get other publishers data too. I want to retrieve data just from 738. I am trying different approaches here, but probably I have to include pub_id inside the publisher schema in some way.

Any clue?

Thanks in advance.

Probably, what I need to query is just this:

db.getCollection('daily_aggregate').find({'publisher.738':{$exists: true}}, {_id: 0, 'publisher' : 1})

It gives me:

1
{
    "publisher" : {
        "738" : {
            "daily" : NumberLong(4),
            "hourly" : {
                "18" : NumberLong(4)
            }
        }
    }
}

2
{
    "publisher" : {
        "738" : {
            "daily" : NumberLong(6),
            "hourly" : {
                "18" : NumberLong(6)
            }
        }
    }
}

3
{
    "publisher" : {
        "43" : {
            "daily" : NumberLong(9),
            "hourly" : {
                "12" : NumberLong(3),
                "19" : NumberLong(6)
            }
        },
        "738" : {
            "daily" : NumberLong(3),
            "hourly" : {
                "12" : NumberLong(3)
            }
        }
    }
}

4
{
    "publisher" : {
        "43" : {
            "daily" : NumberLong(1),
            "hourly" : {
                "12" : NumberLong(1)
            }
        },
        "738" : {
            "daily" : NumberLong(2),
            "hourly" : {
                "12" : NumberLong(2)
            }
        }
    }
}

But I am wondering if this is the best scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM