I understand when 'Exists' and 'Not Exist' return true or false, and I know if it returns false nothing will be retrieved, but if it returns true, what will be retrieved?
Thank you..
It will return the values that you specified in your query (provided you don't have other elements in your WHERE clause that return false and are connected with a logical AND with your existence check.)
In other words: 'EXISTS' or 'NOT EXISTS' works like any other condition in your WHERE clause. Each of them will either return true or false and that will evaluate according to the rules of Boolean algebra.
You can play around with these examples here:
https://www.w3schools.com/sql/sql_exists.asp
Related
So, lets say I have the following structure:
{
value: 'test',
property: 'good'
}
and I want to create a NEW document with property 'good' but only if it does not already exist with that value {property: 'good'}
So running the query will return a new document:
{
value: 'test2',
property: 'good'
}
Pretty much like unique true indexes work, but all in the same query.
I can always find first and check if it returns null and then proceed to create it, but is there any operator to do it into the same query?
Thanks in advance.
I want to return true if a userID already exists and false otherwise from my collection.I have this function but it always returns True.
def alreadyExists(newID):
if db.mycollection.find({'UserIDS': { "$in": newID}}):
return True
else:
return False
How could I get this function to only return true if a user id already exists?
Note: This answer is outdated. More recent versions of MongoDB can use the far more efficient method db.collection.countDocuments. See the answer by Xavier Guihot for a better solution.
find doesn't return a boolean value, it returns a cursor. To check if that cursor contains any documents, use the cursor's count method:
if db.mycollection.find({'UserIDS': { "$in": newID}}).count() > 0
If newID is not an array you should not use the $in operator. You can simply do find({'UserIDS': newID}).
Starting Mongo 4.0.3/PyMongo 3.7.0, we can use count_documents:
if db.collection.count_documents({ 'UserIDS': newID }, limit = 1) != 0:
# do something
Used with the optional parameter limit, this provides a way to find if there is at least one matching occurrence.
Limiting the number of matching occurrences makes the collection scan stop as soon as a match is found instead of going through the whole collection.
Note that this can also be written as follow since 1 is interpreted as True in a python condition:
if db.collection.count_documents({ 'UserIDS': newID }, limit = 1):
# do something
In earlier versions of Mongo/Pymongo, count could be used (deprecated and replaced by count_documents in Mongo 4):
if db.collection.count({ 'UserIDS': newID }, limit = 1) != 0:
# do something
If you're using Motor, find() doesn't do any communication with the database, it merely creates and returns a MotorCursor:
http://motor.readthedocs.org/en/stable/api/motor_collection.html#motor.MotorCollection.find
Since the MotorCursor is not None, Python considers it a "true" value so your function returns True. If you want to know if at least one document exists that matches your query, try find_one():
#gen.coroutine
def alreadyExists(newID):
doc = yield db.mycollection.find_one({'UserIDS': { "$in": newID}})
return bool(doc)
Notice you need a "coroutine" and "yield" to do I/O with Tornado. You could also use a callback:
def alreadyExists(newID, callback):
db.mycollection.find_one({'UserIDS': { "$in": newID}}, callback=callback)
For more on callbacks and coroutines, see the Motor tutorial:
http://motor.readthedocs.org/en/stable/tutorial.html
If you're using PyMongo and not Motor, it's simpler:
def alreadyExists(newID):
return bool(db.mycollection.find_one({'UserIDS': { "$in": newID}}))
Final note, MongoDB's $in operator takes a list of values. Is newID a list? Perhaps you just want:
find_one({'UserIDS': newID})
One liner solution in mongodb query
db.mycollection.find({'UserIDS': { "$in": newID}}).count() > 0 ? true : false
return db.mycollection.find({'UserIDS': newID}).count > 0
This worked for me
result = num.find({"num": num}, { "_id": 0 })
if result.count() > 0:
return
else:
num.insert({"num": num, "DateTime": DateTime })
I am developing an application in Express with Mongo, in which i have to query, whether a document exits in the collection or not. I am doing this:
var dept= req.body.dept;
var name= req.body.name;
mongoose.model('User').find({'dept': dept, 'name': name}, function(err, user){
if(err){
res.render('user/test1');
}else{
res.redirect('/');
}
});
What I want to do is to check if that document exits in the collection and upon true condition, i want to redirect to another page otherwise render the current page. But when I pass the wrong input, even then it goes to the else part and redirects it.
Well you are actually using mongoose, so there is in fact a distinction between what is returned by this specific version ( abtraction ) to what the base driver itself returns.
In the case of mongoose, what is returned is either an array of results or a null value if nothing is found. If you are looking for a singular match then you probably really want findOne() instead of a result array.
But of course the case would be a null result with either function if not returned as opposed to an err result that is not null, which is of course about specific database connection errors rather than simply that nothing was found.
The base driver on the other hand would return a "Cursor" ( or optionally considered a promise ) instead, which can either be iterated or converted to an array like mongoose does via the .toArray() method. The .findOne() method of the base driver similarly returns either a result or a null document where the conditions do not match.
mongoose.model('User').findOne({'dept': dept, 'name': name}, function(err, user){
if(err){
// if an error was actually returned
} else if ( !user ) {
// Nothing matched, in REST you would 404
} else {
// this is okay
}
});
In short, if you want to test that you actually found something, then look at the user value for a value that is not null in order to determine it matched. If it is null then nothing was matched.
So no match is not an "error", and an "error" is in fact a different thing.
I have a MongoDB group query. I udnerstand most of it, but the 'if' condition bit in the 'reduce' function is confusing me. I am not sure what the purpose of that is.
db.users.group({
"initial": {
"countstar": 0
},
"reduce": function(obj, prev) {
if (true != null) if (true instanceof Array) prev.countstar += true.length;
else prev.countstar++;
},
"cond": {
"location": null
}
});
I know what the 'initial' parameter does. I also know what the 'cond' parameter is doing. However, the whole bit inside the 'reduce' parameter is confusing.
Also, what is the equivalent SQL?
It's easier to understand if we reformat it:
db.users.group({
"initial": { "countstar": 0 },
"reduce": function(obj, prev) {
if (true != null) {
if (true instanceof Array)
prev.countstar += true.length;
else
prev.countstar++;
}
},
"cond": { "location": null }
});
Something's definitely wrong with this, because true is a boolean value in Javascript, so the first condition always holds, the second condition never holds, and true.length is undefined. It looks like true should instead by some property of obj. In that case, what the code does, sort of, is sum the lengths of the whatever array property true is supposed to refer to, counting non-array values as length 1 arrays. Where did this code come from? Does it actually work and give you a meaningful result? What's the result that you want to get from this code? I think you should throw the function out. You can do the same thing with aggregation and it will work better. Since you shouldn't use this code and I'm not competent with SQL, I won't try to translate it into SQL.
Which is more accepted practice: making a boolean field for each of multiple (say 3-7) things that could be "on" or "off", or making a single string array field which either contains or does not contain each of the 3-7 things?
Example:
stored -> {green: true, blue: true, red: false, yellow: true}
read -> if collection.find_one(_id).green: // execute code
vs.
stored -> {colors: ['green', 'blue', 'yellow']}
read -> if 'green' in collection.find_one(_id).colors: // execute code
This is an opinion based question, but anyway, it's way better your second approach assuming that if element isn't found in the array will be configured as false or true (depends on the condition), but that approach is something that I could name convention over configuration