sql >> Base de Datos >  >> NoSQL >> MongoDB

Relación Mongodb 1to1 entre subdocumentos

Teniendo en cuenta la "sangría" que estoy usando en la lista, esto puede parecer más largo que lo que estás haciendo, pero en realidad no lo es.

Este es otro muy buen ejemplo del uso de $map como disponible para MongoDB 2.6 y superior. Todavía se usa algo de $unwind , pero las matrices que se "desenrollan" en realidad solo tienen uno elemento en ellos. Entonces, perdone a mi "Highlander" referencias a las que no me pude resistir :)

db.users.aggregate([

    // Match your document or documents
    { "$match": {
        "commentUpvotes.id": 12
    }},

    // Get the one "up-votes" entry that matches
    { "$project": {
        "posts": 1,
        "comments": 1,
        "commentUpVotes": {
            "$setDifference": [
                { 
                    "$map": {
                        "input": "$commentUpvotes",
                        "as": "el",
                        "in": {
                            "$cond": [
                                { "$eq": [ "$$el.id", 12 ] },
                                "$$el",
                                false
                            ]
                        }  
                    }
                },
                [false]
            ]
        }
    }},

    // There is only one!
    { "$unwind": "$commentUpVotes" },

    // Get the one comments entry that matches
    { "$project": {
        "posts": 1,
        "comments": {
            "$setDifference": [
                { 
                    "$map": {
                        "input": "$comments",
                        "as": "el",
                        "in": {
                            "$cond": [
                                { 
                                    "$eq": [ 
                                        { "$substr": [ "$$el.id", 0, 4 ] }, 
                                        "$commentUpVotes.commentId"
                                    ] 
                                },
                                "$$el",
                                false
                            ]
                        }  
                    }
                },
                [false]
            ]
        },
        "commentUpVotes": 1
    }},

    // And there is only one!
    { "$unwind": "$comments" },

    // Get the one post that matches
    { "$project": { 
        "posts": {
            "$setDifference": [
                { 
                    "$map": {
                        "input": "$posts",
                        "as": "el",
                        "in": {
                            "$cond": [
                                { 
                                    "$eq": [ 
                                        "$$el.id", 
                                        "$comments.postId"
                                    ] 
                                },
                                "$$el",
                                false
                            ]
                        }  
                    }
                },
                [false]
            ]
        },
        "comments": 1,
        "commentUpVotes": 1
    }},

    // Optionally group back to arrays. There can be only one!
    { "$group": {
        "_id": "$_id",
        "posts": { "$first": "$posts" },
        "comments": { "$push": "$comments" },
        "commentUpVotes": { "$push": "$commentUpVotes" }
    }}

])

Así que el resultado final sería:

{
    "_id" : ObjectId("539065d3cd0f2aac5f55778e"),
    "posts" : [
            {
                    "title" : "post1",
                    "id" : "123"
            }
    ],
    "comments" : [
            {
                    "id" : 1910,
                    "postId" : "123",
                    "title" : "comment1",
                    "comment" : "some comment",
                    "user" : "user13"
            }
    ],
    "commentUpVotes" : [
            {
                    "id" : 12,
                    "commentId" : "1910",
                    "upvotedBy" : "user91"
            }
    ]
}

Sé que pidió "sin cambios de esquema", pero no es realmente un cambio de esquema para decir que es una buena idea mantener su id valores aquí de un tipo consistente. Actualmente está mezclando números enteros y cadenas en este proceso (espero que sea solo un ejemplo), lo cual no es una buena idea.

Por lo tanto, hay algo de "transmisión limitada" que en realidad está disponible aquí usando $substr , sin embargo, su solución real puede variar en cómo hacer esto realmente. Sugiero enfáticamente arreglar los datos si realmente necesitan arreglarse.

En cualquier caso, un uso bastante bueno para $map