Tomás Juárez
Tomás Juárez

Reputation: 1514

Plain query in mongoDB

I have a collection called constructora that has the following structure:

{
    "_id" : A,
    "edificio" : [
        {
            "_id": X,
            "a" : 48,
            "b" : 59  
        },
        {
            "_id": Y,
            "a" : 8,
            "b" : 5  
        },
        {
            "_id": Z,
            "a" : 0,
            "b" : -1  
        },
        ...
    ]
}

So, I want to make a query that returns, for each sub document (edificio) his parent's _id. An example:

{
    "_id" : X,
    "a" : 48,
    "b" : 59
    "id_constructora" : A
}
{
    "_id" : Y,
    "a" : 8,
    "b" : 5
    "id_constructora" : A
}
{
    "_id" : Z,
    "a" : 0,
    "b" : -1
    "id_constructora" : A
}

How can I do that?

EDIT

Now I'm trying using aggregate, and grouping my query by "edificio_id", so for each document in edificio I can get my desired output:

db.constructora.aggregate(
    [
        { $project : { "_id" : 1, "edificio._id" : 1 } },
        { $group : { _id : "$edificio._id" } }
    ]
).pretty();

But it doesn't work. The output is:

...
{
    "_id" : [
        ObjectId("613339376430333562373466"),
        ObjectId("663736363935393066656236"),
        ObjectId("313933613036363364633832"),
        ObjectId("653135313831633638336436")
    ]
}
{
    "_id" : [
        ObjectId("643531326231663739626465"),
        ObjectId("343231386237333365356461"),
        ObjectId("373461303864636138393263"),
        ObjectId("386433623966653737343962"),
        ObjectId("303863633366376431363335"),
        ObjectId("663833343161643639376161"),
        ObjectId("383833363836663532633733"),
        ObjectId("396330313961353137333166"),
        ObjectId("646535366662363364613837"),
        ObjectId("633937613032656436653965")
    ]
}

Upvotes: 0

Views: 93

Answers (1)

s7vr
s7vr

Reputation: 75934

You can use $unwind to break the embedded array into embedded docs, $addFields to rename and add the _id into the embedded doc followed by $replaceRoot to promote the embedded document to the top level in 3.4 mongo server.

db.constructora.aggregate([
   {$unwind:"$edificio"},
   {$addFields:{"edificio.id_constructora":"$_id"}},
   {$replaceRoot: {newRoot: "$edificio"}}
])

More info here https://docs.mongodb.com/manual/reference/operator/aggregation/replaceRoot/#replaceroot-with-an-array-element

Upvotes: 1

Related Questions