MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Mongodb gibt mehrere Sub-Array-Ergebnisse zurück und schließt andere zurückgegebene Ergebnisse aus

Was Sie brauchen, ist "aggregation" und der $map und der $setDifference Operatoren

db.collection.aggregate([ 
    { 
        "$match": { 
            "node.-user": "Zulu99", 
            "node.-lat": "-37.6787103" 
        }
    },
    { 
        "$project": { 
            "node": { 
                "$setDifference": [{ 
                    "$map": { 
                        "input": "$node",
                        "as": "n", 
                        "in": { 
                            "$cond": [
                                { "$eq": [ "$$n.-user", "Zulu99" ]}, 
                                "$$n", 
                                false 
                            ]
                        } 
                    }
                }, 
                [false]]
            }
        }
    }
])

Ab MongoDB 3.2 können Sie den $filter verwenden Betreiber

db.collection.aggregate([
    { 
        "$match":  { 
            "node.-user": "Zulu99",
            "node.-lat": "-37.6787103"
        }
    }, 
    { "$project": {
        "node": {
            "$filter": {
                "input": "$node",
                "as": "n",
                "cond": { "$eq": [ "$$node.n", "Zulu99" ] }
            }
        }
    }}
])

was ergibt:

{
        "_id" : ObjectId("55acf6187d4c31475417fa62"),
        "node" : [
                {
                        "-id" : "60648717",
                        "-uid" : "46482",
                        "-user" : "Zulu99",
                        "-lat" : "-37.6796337",
                        "-lon" : "144.9220639",
                        "-timestamp" : "2009-12-12T21:29:36Z",
                        "-visible" : "true",
                        "-version" : "2",
                        "-changeset" : "3358816"
                },
                {
                        "-id" : "60648718",
                        "-timestamp" : "2009-12-12T21:29:35Z",
                        "-uid" : "46482",
                        "-version" : "2",
                        "-changeset" : "3358816",
                        "-user" : "Zulu99",
                        "-visible" : "true",
                        "-lat" : "-37.6787103",
                        "-lon" : "144.9224609"
                }
        ]
}