logo
down
shadow

How do I query MongoDB from PHP with IFNULL() expression inside WHERE?


How do I query MongoDB from PHP with IFNULL() expression inside WHERE?

By : Yvain Demoll'
Date : November 22 2020, 09:00 AM
it should still fix some issue Create a variable to hold the JavaScript function that returns the null coalescing expression. Here's some sample test documents to test this in mongo shell:
code :
db.test.insert([
    { _id: 1, field_id: 0 },
    { _id: 2, test_field: 1 },
    { _id: 3, field_id: null },    
    { _id: 4, field_id: 3 }
])
db.test.find({ "$where": "function() { return (this.field_id || 0) == 0; }" })
/* 0 */
{
    "_id" : 1,
    "field_id" : 0
}

/* 1 */
{
    "_id" : 2,
    "test_field" : 1
}

/* 2 */
{
    "_id" : 3,
    "field_id" : null
}
<?php

/**
 * @var MongoDB
 */
$db = $this->getMongoDbHandler();

/**
 * @var MongoCollection
 */
$coll = $db->selectCollection('myColl');

/**
 * @var JavaScript code
 */
$js = "function() { return (this.field_id || 0) == 0; }" ;

/**
 * @var MongoCursor
 */ 
$cursor = $coll->find(array('$where' => $js));

foreach ($cursor as $doc) {
    var_dump($doc);
}

?>


Share : facebook icon twitter icon
MongoDb cannot get result from $ifNull

MongoDb cannot get result from $ifNull


By : SK94
Date : March 29 2020, 07:55 AM
this will help From BatScream in the comments above; you can simply replace by checking
code :
if(fence.properties.d.v[0]){//code to replace}
MongoDB $ifNull conditional with mgo

MongoDB $ifNull conditional with mgo


By : 叶PP
Date : March 29 2020, 07:55 AM
hop of those help? Your news_count projection works, the error is somewhere else in the code which you haven't posted.
See this full, working example:
code :
cu := sess.DB("").C("users")
cnc := sess.DB("").C("newscounter")

he := func(err error) {
    if err != nil {
        panic(err)
    }
}

he(cu.Insert(
    bson.M{
        "_id":      bson.ObjectIdHex("592400188d84961b7f34b0ce"),
        "username": "randomuser1",
        "location": bson.M{
            "type":        "Point",
            "coordinates": []interface{}{-17.634135, 65.705665},
        },
    },
    bson.M{
        "_id":      bson.ObjectIdHex("592400188d84961b7f34b0cd"),
        "username": "randomuser2",
        "location": bson.M{
            "type":        "Point",
            "coordinates": []interface{}{-17.282573, 63.755657},
        },
    },
))
he(cnc.Insert(
    bson.M{
        "_id":   bson.ObjectIdHex("592400188d84961b7f34b0cd"),
        "count": 14,
    },
))

pipe := cu.Pipe([]bson.M{
    {
        "$geoNear": bson.M{
            "near": bson.M{
                "type":        "Point",
                "coordinates": []interface{}{-21.861198, 64.120877},
            },
            "distanceField": "distance",
            "maxDistance":   123456789,
            "spherical":     true,
        },
    },
    {
        "$sort": bson.M{"distance": 1},
    },
    {
        "$lookup": bson.M{
            "from":         "newscounter",
            "localField":   "_id",
            "foreignField": "_id",
            "as":           "news_count",
        },
    },
    {
        "$unwind": bson.M{
            "path": "$news_count",
            "preserveNullAndEmptyArrays": true,
        },
    },
    {
        "$project": bson.M{
            "id":       1,
            "username": 1,
            "distance": 1,
            "news_count": bson.M{
                "$ifNull": []interface{}{"$news_count.count", 0},
            },
        },
    },
})

it := pipe.Iter()

fmt.Println()
m := bson.M{}
for it.Next(&m) {
    fmt.Println(m)
    fmt.Println()
}
he(it.Err())
map[_id:ObjectIdHex("592400188d84961b7f34b0cd") username:randomuser2 distance:227534.08191011765 news_count:14]

map[username:randomuser1 distance:266222.98643136176 news_count:0 _id:ObjectIdHex("592400188d84961b7f34b0ce")]
MongoDB - how to use $ifNull only on a field that exists

MongoDB - how to use $ifNull only on a field that exists


By : roriz87
Date : March 29 2020, 07:55 AM
To fix this issue I'm using $lookup, which may or may not return something. But if it does, i need to check the looked up value and check a specific field to see if it is null, and if it is, set it to something. , You can use newer $lookup syntax to achieve the expected result
code :
db.collection.aggregate([
  { "$lookup": {
    "from": "item_templates",
    "let": { "based_on": "$based_on" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$_id", "$$based_on"] }}},
      { "$addFields": {
        "image.url": {
          "$ifNull": [
            "$image.url",
            "http://via.placeholder.com/400x700/d3d3d3/000000/?text=No%20Image&"
          ]
        }
      }}
    ],
    "as": "template"
  }}
])
Using another query inside IFNULL() function

Using another query inside IFNULL() function


By : Reinier
Date : March 29 2020, 07:55 AM
hope this fix your issue I don't understand why you would use ifnull(). Does this do what you want?
code :
SELECT payment_method
FROM payment_plan 
WHERE ptid = 100 AND
      validfrom <= CURDATE() AND
      validto > CURDATE() AND
      payment_method IN ('CC', '*') ;
ORDER BY (payment_method <> '*') desc
LIMIT 1
mongodb ifNull on lookup

mongodb ifNull on lookup


By : x64
Date : March 29 2020, 07:55 AM
I wish this help you We can set null value using $unwind keyword after checking value of adsys and set null value if adsys is not defined.
code :
db.tableName.aggregate(
    [
        {
            '$lookup': {
                'from': 'advertisers',
                'localField': 'title',
                'foreignField': 'title',
                'as': 'adsys'
            }
        },
        { "$unwind": { path: "$adsys", preserveNullAndEmptyArrays: true } },
        {
            '$project': {
                'title': 1,
                'adsys': { '$ifNull': ["$adsys", "NULL"] }
            }
        }
    ]);
Related Posts Related Posts :
  • Populate form from database
  • Got blank value in update query
  • PHP show message based on user had attach file or not attach file
  • Outline a transparent image using imagick PHP
  • If statement based on last digit of php variable number
  • make popup when post data on the same page
  • How to check email id's with specific domain from the array of email id's in PHP?
  • Dropdown list displays no value
  • Change openssl version in MAMP
  • How to use ob_start() in PHP project while using of Front Controller pattern
  • How do I implement search filter query using mongodb?
  • Android retrieve data from php org.json.JSONArray cannot be converted to JSONObject
  • Error Get request PHP
  • Update datepicker value based on php condition
  • Codeigniter Model loading error
  • How to sort varchar id on basis integer in it using mysql
  • Trial Balance Update accounts
  • Always return user details as json every time user login in laravel 5
  • join table on postgres with php
  • How to check for empty values with in_array WITH EXCEPTIONS?
  • How to replace return carriage in json string made from mysql and php?
  • Intl extension not getting loaded
  • PHP How to echo a 3-dim array
  • How to extend and modify a vendor model in Laravel 5?
  • How to change the number of posts that Wordpress JSON Api loads per page
  • how to validate dynamic text boxes using jquery
  • PHP undefined index id error
  • How to Parse xml data using php
  • getJSON parser cannot process JSON output from PHP file
  • Using Redis on Azure with Symfony2
  • php proc_open file descriptor in bash command
  • Trying to create a generalized function in PHP 5.2, error message not showing
  • Merging multiple rows with same field in column
  • Move "in stock" up on Woocommerce product page
  • Wrong reference path to Mail.php
  • phalcon volt bitwise operatios?
  • How to switch between tab when form submitting in same php file?
  • wp all import script to custom post image gallery
  • Storing a single password within in a PHP file instead of a database of users
  • get increment decrement day once clicked button
  • sql check for duplicates returning bool false?
  • Webmaster tools api dimensions
  • Seeding table using model factory not saving
  • How do I save associated entities in Doctrine 2?
  • fopen $_SERVER[REQUEST_URI]
  • RedBean One to Many Attribute Not Working
  • Safely passing ids to form action?
  • Php array explode a char
  • PHP MySQL Login Failure
  • can't get file_exists to work
  • Array PHP, Check if exist multiple elements to another array
  • Can array_walk be nested in php?
  • Notice: Use of undefined constant DIR - assumed '_DIR_'
  • Getting a weird 500 error with ajax
  • How can I filter an array of strings to remove elements that are prefixes of other elements?
  • Duplicate entries when assigning custom id to Laravel Model
  • AJAX call not returning php file command
  • How to make "INNER JOIN" sql query based on my requirements
  • Routes by DNS names in Symfony2 project
  • Laravel 5.1 Mysql NULL
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co