T
T
timkit802014-03-31 07:34:48
JavaScript
timkit80, 2014-03-31 07:34:48

How to sort fields after applying $setUnion mongoDB?

There is a collection:

{
    "_id" : ObjectId("5338ec2a5b5b71242a1c911c"),
    "people" : [ 
        {
            "name" : "Vasya"
        }, 
        {
            "age" : "30"
        }, 
        {
            "weight" : "80"
        }
    ],
    "animals" : [ 
        {
            "dog" : "Sharick"
        }, 
        {
            "cat" : "Barsik"
        }, 
        {
            "bird" : "parrot"
        }
    ]
},
{
    "_id" : ObjectId("5338ec7f5b5b71242a1c911d"),
    "people" : [ 
        {
            "name" : "Max"
        }, 
        {
            "age" : "32"
        }, 
        {
            "weight" : "78"
        }
    ],
    "animals" : [ 
        {
            "dog" : "Borbos"
        }, 
        {
            "cat" : "Murka"
        }, 
        {
            "bird" : "Eagle"
        }
    ]
}

Query:
db.tmp.aggregate({$project:{"union":{$setUnion:["$people","$animals"]}}})
and result:
{
    "result" : [ 
        {
            "_id" : ObjectId("5338ec2a5b5b71242a1c911c"),
            "union" : [ 
                {
                    "bird" : "parrot"
                }, 
                {
                    "name" : "Vasya"
                }, 
                {
                    "age" : "30"
                }, 
                {
                    "weight" : "80"
                }, 
                {
                    "dog" : "Sharick"
                }, 
                {
                    "cat" : "Barsik"
                }
            ]
        }, 
        {
            "_id" : ObjectId("5338ec7f5b5b71242a1c911d"),
            "union" : [ 
                {
                    "name" : "Max"
                }, 
                {
                    "age" : "32"
                }, 
                {
                    "weight" : "78"
                }, 
                {
                    "bird" : "Eagle"
                }, 
                {
                    "dog" : "Borbos"
                }, 
                {
                    "cat" : "Murka"
                }
            ]
        }
    ],
    "ok" : 1
}

How can I make sure that the fields of each entry in the result array are displayed in the same order, and not out of order?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question