logo
down
shadow

How to slice find result with php and mongo?


How to slice find result with php and mongo?

By : Ido
Date : November 17 2020, 01:00 AM
I hope this helps . Here is a simplest/minimal example of pagination. I am showing you only the code you are struggling with. This is not a complete working pagination code. Rest of it you can write yourself I guess.
code :
$skip_results = (int)($results_per_page * ($page_number - 1));
$cursor = $collection->find($query)->limit($results_per_page)->skip($skip_results);


Share : facebook icon twitter icon
In String.prototype.slice(), should .slice(0,-0) and .slice(0,+0) output the same result?

In String.prototype.slice(), should .slice(0,-0) and .slice(0,+0) output the same result?


By : Brendan Johnson
Date : March 29 2020, 07:55 AM
I wish did fix the issue. From a mathematical perspective there is no negative zero. Positive is any number greater than zero, and negative is any number smaller than zero. Zero is neither of those. So I guess the behaviour you described is correct.
code :
var counter = 1;
var myText = counter + " unit" + (counter > 1 ? "s" : "");
Mongo Aggregate find element in array based on match/sort/slice/group query

Mongo Aggregate find element in array based on match/sort/slice/group query


By : Aad Wildeboer
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , You can try below aggregation.
Added two groups one group each for count by type and other for count by user.
code :
[
  {"$match":{"createdDate":{"$gte":"2018-01-01 00:00:00","$lte":"2018-03-02 23:59:59"}}},
  {"$unwind":"$visits"},
  {"$match":{"visits.date":{"$gte":"2018-01-01 00:00:00","$lte":"2018-03-02 23:59:59"}}},
  {"$sort":{"visits.date":-1}},
  {"$group":{"_id":{"_id":"$_id","user":"$user"},"latestvisit":{"$first":"$visits"}}},
  {"$group":{"_id":{"user":"$_id.user","type":"$latestvisit.type"},"visits":{"$sum":1}}},
  {"$group":{
    "_id":"$_id.user",
    "type":{"$push":{"type":"$_id.type","visits":"$visits"}},
    "count":{"$sum":"$visits"}
  }}
]
Is there a way to get slice as result of Find()?

Is there a way to get slice as result of Find()?


By : T. Doğan
Date : March 29 2020, 07:55 AM
wish helps you The result of a MongoDB find() is always a list of documents. So if you want a list of values, you have to convert it manually just as you did.
Using a custom type (derived from string)
code :
type Username string

func (u *Username) SetBSON(raw bson.Raw) (err error) {
    doc := bson.M{}
    if err = raw.Unmarshal(&doc); err != nil {
        return
    }
    *u = Username(doc["username"].(string))
    return
}
c := mongodb.DB("mybase").C("mycollection") // Obtain collection

var uns []Username
err = c.Find(nil).Select(bson.M{"username": 1, "_id": 0}).All(&uns)
if err != nil {
    fmt.Println(err)
}
fmt.Println(uns)
var uns []string
it := c.Find(nil).Select(bson.M{"username": 1, "_id": 0}).Iter()
defer it.Close()
for doc := (bson.M{}); it.Next(&doc); {
    uns = append(uns, doc["username"].(string))
}
if err := it.Err(); err != nil {
    fmt.Println(err)
}
fmt.Println(uns)
Mongo db query find doesn't show array result

Mongo db query find doesn't show array result


By : James Carter
Date : March 29 2020, 07:55 AM
this will help So the issue is with where you are initializing your array, put it before your find. I edited your code, take a look at it.
Also your main issue is farms is an array therefore farms._id doesn't exist. find finds an array if you want to find only 1 then you use findOne
code :
router.post('/login', function(req, res) {
User.findOne({ username: req.body.username}, function(err, user) {
    if (err){
        return res.status(500).send('Error on the server.');
    }
    if (!user){
        return res.status(401).send({status: 'ko', error: {msg: 'The username ' + req.body.username + ' is not associated with any account.'}});
    }
    var passwordIsValid = bcrypt.compareSync(req.body.password, user.password);
    //if (!passwordIsValid) return res.status(401).send({ auth: false, token: null });
    if (!passwordIsValid){
        return res.status(401).send({status: 'ko', error: {msg:'Authentication failed. Wrong password.',auth: false, token: null}});
    }
    // Make sure the user has been verified
    if (!user.isVerified){
        return res.status(401).send({status: 'ko', error: {type: 'not-verified', msg: 'Your account has not been verified.'}});
    }
    if (!user.statusUser){
        return res.status(401).send({status: 'ko', error: {msg: 'The username ' + req.body.username + ' is blocked by Admin'}});
    }
    // if user is found and password is valid
    // create a token
    var token = jwt.sign({ id: user._id }, config.secret, {
      expiresIn: 86400 // expires in 24 hours
    });

    // inserimento farm id //
    Farm.find({ farmId: user.farmId}, (err, farms) => {
        var identify_farm = [];

        farms.forEach(function(farm){
           console.log(farm);
           if (farm) {
            identify_farm.push(farm._id);
           }
        })

    // inserimento farm id //

    // return the information including token as JSON
    req.session.user = user;
    res.status(200).send({status: 'ok', data: {auth: true, token: token, farmId: user.farmId, roles: user.roles, id_utente: user._id, identify_farms: identify_farm}});
    });
});
});
Mongo DB aggregate - keep results even if match didn't find result

Mongo DB aggregate - keep results even if match didn't find result


By : pixius
Date : March 29 2020, 07:55 AM
With these it helps You could do that by using $addFields & $cond which conditionally adds same field Varas or null, So add this stage as last stage to your existing pipeline :
code :
{$addFields : {Varas: { $cond: [ {$eq : ['$Varas.CodVara', '9001']}, '$Varas', null ] }}}
db.getCollection('Tribunais').aggregate([
    {
        $match: {
            Cod: '5'
        }
    },
    {
        $unwind: '$Orgaos'
    },
    {
        $match: {
            'Orgaos.Siglas': 'MS'
        }
    },
    {
        $lookup: {
            'from': 'Varas',
            'localField': 'Orgaos.Varas',
            'foreignField': '_id',
            'as': 'Varas'
        }
    },
    {
        $unwind: '$Varas'
    }, { $addFields: { Varas: { $cond: [{ $eq: ['$Varas.CodVara', '9001'] }, '$Varas', null] } } }
])
Related Posts Related Posts :
  • Find TimeDiff between two dates
  • Get Values From Multidimensional PHP Array inside Javascript
  • Static HTML, CSS, and JS to backend admin access
  • How can I manipulate HTML tags in PHP?
  • When to use Else and when to use Elseif?
  • PHP regex which matches only strings with specific endings
  • Tablet detection with detect mobile browser script?
  • Execute mulltiple expressions in conditional operator
  • php \n new line no show well
  • How to add Smarty templating engine to CodeIgniters 3 framework?
  • Am I maxing out possible data insert
  • Redirect to homepage without changing address bar URL
  • What is the best user-Id Value for a MySql "users" table
  • PHP $_COOKIE is only available in one directory
  • php regular expressions documantation
  • cannot import too large sql file to mysql
  • not getting appilcation/json in content-type in header
  • Only the first data display from my database but other shows but not on a table
  • Is it possible to have a print button link as the content of the mail
  • how to extract full mail address in imap php
  • Alternative to output buffering to put eval'd code into a variable
  • how to run wordpress php snippet mysql update command from ssh and/ultimately cron
  • how to get xml tag by name
  • ModSecurity maximum post limits (PCRE limit errors)
  • Call controller/action in event listener
  • How to improve performance of contacting WebService?
  • PHP nest variable in echoed string that contains a HTML tag in the end
  • Multiple Ajax request for PHP framework
  • Debug Info from Moodle Plugin
  • passing variables through page
  • Passing PHP $result data to Javascript
  • cakePHP File Download was not found or not readable
  • batch waiting until script finishes
  • PHP variables and anchors in URL
  • php eTag generation using php
  • How to check whether the array is an Integer or Not?
  • Is it possible to install Doctrine without PEAR or Composer? If so, how?
  • Call view script of (parent) Abstract controller Zend
  • Curl PHP cannot display amazon
  • Symfony, getters and setters vs magic methods
  • Using 'continue' PHP instruction outside the loop
  • AJAX POST return data not appearing
  • Can I query relations using an INNER JOIN instead of two queries in Eloquent?
  • Looping through dynamic form fields and inserting into database
  • My php code can't select mysql auto_increment value
  • Store Angularjs form data in database using php
  • I want to run my sh file continuously even if I close my Putty connection
  • file_get_contents equivalent for gzipped files
  • Include PHP file with jQuery
  • php curl headers do not return from website?
  • How to find out, if facebook ID is a user, group or page
  • Connect webhost database to android database
  • preg_match get div content with class
  • Upload multiple files in Laravel 4
  • Count array numbers in multidimensional array
  • PHP Date diff with a difference
  • Search Customer by custom field in Netsuite
  • Is it possible to hide/encode/encrypt php source code and let others have the system?
  • list items to be displayed using php code and array
  • check if row exists mysqli
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org