logo
down
shadow

MongoDB Calculate Values from Two Arrays, Sort and Limit


MongoDB Calculate Values from Two Arrays, Sort and Limit

By : James Mendoza
Date : November 21 2020, 09:01 AM
it fixes the issue Current Processing is mapReduce
If you need to execute this on the server and sort the top results and just keep the top 100, then you could use mapReduce for this like so:
code :
db.test.mapReduce(
    function() {
        var input = [0.1,0.3,0.4];
        var value = Array.sum(this.vals.map(function(el,idx) {
            return Math.abs( el - input[idx] )
        }));

        emit(null,{ "output": [{ "_id": this._id, "value": value }]});
    },
    function(key,values) {
        var output = [];

        values.forEach(function(value) {
            value.output.forEach(function(item) {
                output.push(item);
            });
        });

        output.sort(function(a,b) {
            return a.value < b.value;
        });

        return { "output": output.slice(0,100) };
    },
    { "out": { "inline": 1 } }
)
{
    "results" : [
        {
            "_id" : null,
            "value" : {
                "output" : [
                    {
                        "_id" : ObjectId("56558d93138303848b496cd4"),
                        "value" : 2.2
                    },
                    {
                        "_id" : ObjectId("56558d96138303848b49906e"),
                        "value" : 2.2
                    },
                    {
                        "_id" : ObjectId("56558d93138303848b496d9a"),
                        "value" : 2.1
                    },
                    {
                        "_id" : ObjectId("56558d93138303848b496ef2"),
                        "value" : 2.1
                    },
                    {
                        "_id" : ObjectId("56558d94138303848b497861"),
                        "value" : 2.1
                    },
                    {
                        "_id" : ObjectId("56558d94138303848b497b58"),
                        "value" : 2.1
                    },
                    {
                        "_id" : ObjectId("56558d94138303848b497ba5"),
                        "value" : 2.1
                    },
                    {
                        "_id" : ObjectId("56558d94138303848b497c43"),
                        "value" : 2.1
                    },
                    {
                        "_id" : ObjectId("56558d95138303848b49842b"),
                        "value" : 2.1
                    },
                    {
                        "_id" : ObjectId("56558d96138303848b498db4"),
                        "value" : 2.1
                    }
                ]
            }
        }
    ],
    "timeMillis" : 1758,
    "counts" : {
            "input" : 10000,
            "emit" : 10000,
            "reduce" : 100,
            "output" : 1
    },
    "ok" : 1
}
db.test.aggregate([
    { "$unwind": { "path": "$vals", "includeArrayIndex": "index" }},
    { "$group": {
        "_id": "$_id",
        "result": {
            "$sum": {
                "$abs": {
                    "$subtract": [ 
                        "$vals", 
                        { "$arrayElemAt": [ { "$literal": [0.1,0.3,0.4] }, "$index" ] } 
                    ]
                }
            }
        }
    }},
    { "$sort": { "result": -1 } },
    { "$limit": 100 }
])
{ "_id" : ObjectId("56558d96138303848b49906e"), "result" : 2.2 }
{ "_id" : ObjectId("56558d93138303848b496cd4"), "result" : 2.2 }
{ "_id" : ObjectId("56558d96138303848b498e31"), "result" : 2.1 }
{ "_id" : ObjectId("56558d94138303848b497c43"), "result" : 2.1 }
{ "_id" : ObjectId("56558d94138303848b497861"), "result" : 2.1 }
{ "_id" : ObjectId("56558d96138303848b499037"), "result" : 2.1 }
{ "_id" : ObjectId("56558d96138303848b498db4"), "result" : 2.1 }
{ "_id" : ObjectId("56558d93138303848b496ef2"), "result" : 2.1 }
{ "_id" : ObjectId("56558d93138303848b496d9a"), "result" : 2.1 }
{ "_id" : ObjectId("56558d96138303848b499182"), "result" : 2.1 }
var bulk = db.test.initializeUnorderedBulkOp();

var x = 10000;

while ( x-- ) {
    var vals = [0,0,0];

    vals = vals.map(function(val) {
        return Math.round((Math.random()*10),1)/10;
    });

    bulk.insert({ "vals": vals });

    if ( x % 1000 == 0) {
        bulk.execute();
        bulk = db.test.initializeUnorderedBulkOp();
    }
}


Share : facebook icon twitter icon
|MongoDB| How to sort and limit embedded arrays? embedded array pagination

|MongoDB| How to sort and limit embedded arrays? embedded array pagination


By : John McCreedy
Date : March 29 2020, 07:55 AM
hope this fix your issue If I understand, you want to find a post by id and return it with only the last 2 comments.
You were not so far, the solution is a combination of your 2 trials :
code :
db.posts.aggregate( 
  {$match: {_id: new ObjectId("52707a234f2044b7f2d22083")}}, 
  {$unwind: "$comments"}, 
  {$sort: {"comments.createdAt": -1}},
  {$limit: 2},
  {"$group": {"_id": "$_id", "comments": {"$push": "$comments"}}}
)
In Spring-data-Mongodb, I'm not able to specify limit values to limit the number of results

In Spring-data-Mongodb, I'm not able to specify limit values to limit the number of results


By : user2638302
Date : March 29 2020, 07:55 AM
this will help Using the repository abstraction allows you to add a Pageable parameter (will be automatically picked up for query execution) to the method signature.
code :
@Query(value = "{location :{ $nearSphere :{$geometry : {type : \"Point\", coordinates : [?1, ?0] },  $maxDistance :?2}}")
List<User> search(float latitude, float longitude, float radius, Pageable page);
//get the first 10 matching results
userRepository.search(37.802066, -122.377347, 10, new PageRequest(0,10));
How to use $limit and $sort with Q.nbind() in mongoDB

How to use $limit and $sort with Q.nbind() in mongoDB


By : Beginner
Date : March 29 2020, 07:55 AM
Hope that helps I am using Q module in my app. I want to use $limit and $sort function for my query for mongoDB, I am also using Q.nbind() for making query , This is very simple just have a look at following code:
code :
    var q = require('q');
    var findSomeThing = q.nbind(SomeThing.find,SomeThing);

    SomeThing({"someId":"someIdValue"},{},{limit:2}).done(function(data){

        //2 records will be retrieved here
        console.log(data);


    });
mongodb sort with skip and limit not sort the record according to index

mongodb sort with skip and limit not sort the record according to index


By : Nymad
Date : March 29 2020, 07:55 AM
I hope this helps you . you need to move $sort before $limit and $skip
as doing $limit you are limiting random documents from collection and next pipeline entries are based on random input
What are the maximum values accepted by .limit() method and $limit aggregation operation in mongodb

What are the maximum values accepted by .limit() method and $limit aggregation operation in mongodb


By : Andrew
Date : March 29 2020, 07:55 AM
wish of those help From the docs for cursor.limit():
Related Posts Related Posts :
  • mongodb update multiple records from command line
  • How to override the document in MongoDB
  • mongodb delete nested object without knowledge of object nodes
  • Is it possible use MongoDb capped collection with phalcon Collection models
  • What do 1 and -1 stand for in mongoose compound indexes?
  • select documents grouped by field
  • MongoDB print distance between two points
  • Mongodb function TypeError
  • Making POST using Instagram/Maker through IFTTT not requesting API url
  • Mongo running slow on Amazon EC2
  • How to map two `future` results in Scala/ReactiveMongo?
  • One query to get parent of document with id
  • Combine three different Aggregate into a single one
  • Remote MongoDB access through Cloud 9 gives login failed exception
  • How to link one model to other in mongo
  • Get length of array within array mongodb
  • How to get multi matching filters count in mongoDB
  • remove element from embedded document in mongodb
  • Mongodb Map-Reduce
  • Saving value passed with variable as numeric value instead of string value
  • mongodb insert unexpected identifier
  • Manually convert embedded documents to references in MongoDB
  • Elastic Beanstalk Deployment with MongoDB
  • How to set result of query as array with mongoose/mongodb
  • How to project specific fields from a document inside an array?
  • Add field (boolean) to returned objects, when a specified value is in array, without including the array itself
  • MongoDB: Find and then modify the result depending on if certain value in field array
  • Meteor: List all collections on the server
  • How can you set a MongoDB write concern at database level that cannot be overridden?
  • Issues during repset members syncing
  • Can we save new record in decending order in mongodb
  • Mongo DB : remove document from collection
  • How to sort by a specific criteria the top X documents already sorted with mongodb?
  • MongoDB: Find and then modify the resulting object
  • MongoDB .populate
  • mongodb query documents by specifying range of dynamic key data
  • How to access object property in mongoose?
  • made a mistake: document collection is an embedded function
  • MongoDB creates empty document
  • Meteor collection (MongoDB) update very poor performance
  • Meteor reactive issue between minomongo and publisher
  • In Falcor how to work with database?
  • mongodb - sort results such that a subset are retrieved first
  • Mongoose update: obtaining pushed subdocument's _id
  • Best database for multiple-column indexes?
  • Datanucleus mongodb references
  • MongoDB throwing error Module not found: 'module'
  • How to connect to remote MongoDB with mongo-connector?
  • Mongoose why would you use populate over another find?
  • mongodb unwind array nested inside an array of documents
  • find() and findOne() methods in MongoDB showing different results
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co