Hello i would like to display n countries with the oldest date in field independence but without null value.
I have something like this but i dont know how to exclude all null values.
db.countries.find({}, {
"independence": 1,
"_id": 0
}).sort({
"independence": 1
}).limit(10);
this my collection
{
"name" : "Example",
"code" : "AXB",
"independence" : null,
}
You can use $exists to select documents where independence field is present:
db.countries.find({
independence: {
$exists: true
}
}, {
"independence": 1,
"_id": 0
}).sort({
"independence": 1
}).limit(10);
If independence field can exist with null value and you need to fetch documents where that field is a date then you can use $type:
db.countries.find({
independence: {
$type: "date"
}
})
Related
I have a JSON in MongoDB and I am trying to check if at least one of the items in the JSON doesn't contain a specific field.
{
"_id" : 12345,
"orderItems" : [
{
"itemId" : 45678,
"isAvailable" : true,
"isEligible" " false
},
{
"itemId" : 87653,
"isAvailable" : true
}
]
}
So in the above JSON, since the 2nd one under order items doesn't contain iseligible field, I need to get this _id.
I tried the below query so far, which didnt work:
db.getCollection('orders').find({"orderItems.iseligible":{$exists:false})
You can use $elemMatch to evaluate the presence of the nested key. Once that's accomplished, project out the _id value.
db.orders.find({
orderItems: {
$elemMatch: {
"isEligible": {
$exists: false
}
}
}
},
{
_id: 1
})
Here is a Mongo playground with the finished code, and a similar SO answer.
I have a document like this:
{
"_id" : "4mDYgt6gID",
...
"MultipleChoiceQuestions" : [
{
...
"LeadInFile" : null,
...
},
{
...
"LeadInFile" : 'some string',
...
}
],
...
}
How do I query for any documents that have a non-null value in LeadInFile?
I'm trying different things, currently something like this
db.getCollection('QuizTime:Quizzes').find({"MultipleChoiceQuestions": [{ "LeadInFile": { $ne: null}}]});
Is returning 0 records.
The current form of the query is saying:
Find documents where MultipleChoiceQuestions is [{ "LeadInFile": { $ne: null}}]
Try using dot notation; this is used to access elements of an array or fields in an embedded document. For example:
db.getCollection('QuizTime:Quizzes').find({
"MultipleChoiceQuestions.LeadinFile" : { "$ne" : null }
})
I am trying to query my Mongo database to display all values from a certain collection, sorted by all the values of a certain key. For example, I have the collection:
{
"id":"1235432",
"name":"John Smith",
"occupation":"janitor",
"salary":"30000"
},
{
"id":"23412312",
"name":"Mathew Colins",
"occupation":"janitor"
"salary":"32000"
},
{
"id":"7353452",
"name":"Depp Jefferson",
"occupation":"janitor"
"salary":"33000"
},
{
"id":"342434212",
"name":"Clara Smith",
"occupation":"Accountant",
"salary":"45000"
},
{
"id":"794563452",
"name":"Jonathan Drako",
"occupation":"Accountant",
"salary":"46000"
},
{
"id":"8383747",
"name":"Simon Well",
"occupation":"Accountant",
"salary":"41000"
}
and I am trying to display only the TOP 2 with highest salary by occupation. My query looks something like this at the moment:
Stats.find({occupation:{$exists:true}}).populate('name').sort({salary:1}).limit(2)
by that only returns only 1 result instead of one from each occupation.
How can I change my query to display the top 2 of each occupation by salary range?
You can use $aggregate as mentioned below.
db.collectionName.aggregate({$match:{occupation:{$exists:true}}},
{ $sort: {"salary":-1}},
{ $limit: 2},
{ $project: {"name":1,"salary":1,_id:0} })
Output JSON:
{"name" : "Jonathan Drako",
"salary" : "46000"},
{"name" : "Clara Smith",
"salary" : "45000"}
My database schema is somewhat like
{
"_id" : ObjectId("1"),
"createdAt" : ISODate("2017-03-10T00:00:00.000+0000"),
"user_list" : [
{
"id" : "a",
"some_flag" : 1,
},
{
"id" : "b",
"some_flag" : 0,
}
]
}
What I want to do is get the document where id is b & some_flag for the user b is 0.
My query is
db.collection.find({
'createdAt': {
$gte: new Date()
},
'user_list.id': 'b',
'user_list.some_flag': 1
}).sort({
createdAt: 1
})
When I run the query in shell. It returns the doc with id 1(which it shouldn't as the value of some_flag for b is 0)
The thing happening here is,
the query 'user_list.id': user_id matches with the nested object where "id" : b
'user_list.some_flag': 1 is matched with some_flag of nested object where "id": a (as the value of some_flag is 1 here)
What modifications should I make to compare the id & some_flag for the same nested object.
P.S. the amount of data is quite large & using aggregate will be a performance bottleneck
You should be using $elemMatch otherwise mongoDB queries are applied independently on array items, so in your case 'user_list.some_flag': 1 will be matched to array item with id a and 'user_list.id': 'b' will match array item with id b. So essentially if you want to query on array field with and logic use $elemMatch as following:
db.collection.find({
'createdAt': {
$gte: new Date()
},
user_list: {$elemMatch: {id: 'b', some_flag: 1}} // will only be true if a unique item of the array fulfill both of the conditions.
}).sort({
createdAt: 1
})
you need to try something like :
db.collection.find({
'createdAt': {
$gte: new Date()
},
user_list: {
$elemMatch: {
id: 'b',
some_flag: 1
}
}
}).sort({
createdAt: 1
});
This will match only user_list entries where _id is b and someflag is 1
I inputed a parameter, and using mongodb.
My query is
db.collections.find({"tags":parameter});
I want to run query, when parameter is "" (null or "").
It will be
db.collections.find({"tags":""});
It is returned empty value.
How can I use input parameter null or "" in mongoDB?
EDIT
I'm sorry. I'm beginner in here, so sorry.
I want to get all the values returned when I type null
For example, it looks like this my collections,
collections
{
"_id": 0,
"tags": ["happy", "sad", "nice", "bad"]
},
{
"_id": 1,
"tags": ["bad", "gloomy"]
}
I want the same result as below.
> Db.collections.find ({"tags": ""})
{
"_id": 0,
"tags": ["happy", "sad", "nice", "bad"]
},
{
"_id": 1,
"tags": ["bad", "gloomy"]
}
// Return all collections.
> Db.collections.find ({"tags": "happy"})
{
"_id": 0,
"tags": ["happy", "sad", "nice", "bad"]
}
// Return matching collections.
but, db.collections.find ({"tags": ""}) brings out the results of that result is empty.
How can I print out all the results when I enter a null value?
Since a null value can be represented in several ways, depending on the language that wrote to the database in the first place, you need to use a combinations of things. Your query will need to look something like
db.collection.find({$or:[{"tags":{"$type":"null"}}, {"tags": {"$exists":false}}, {"tags":""}]})
Since BSON has a concept of Null, we have type check to see if the field exists but simply has no value. In addition to this, the field could not exist at all, so this must be explicitly checked for. Finally, depending on the language and the way the field was serialized, an empty string is a possibility.
Note that
{"tags":null}
and
{"tags":{"$type":"null"}}
are essentially the same thing.
Here is a quick example
> db.test.insert({"abc":null})
WriteResult({ "nInserted" : 1 })
> db.test.find()
{ "_id" : ObjectId("56670b3072f096ee05a72063"), "abc" : null }
> db.test.find({"abc":{$type:10}})
{ "_id" : ObjectId("56670b3072f096ee05a72063"), "abc" : null }
> db.test.find({"abc":{$type:"null"}})
{ "_id" : ObjectId("56670b3072f096ee05a72063"), "abc" : null }
> db.test.find({"abc":null})
{ "_id" : ObjectId("56670b3072f096ee05a72063"), "abc" : null }
db.test.find({$or:[{"tags":{"$type":"null"}}, {"tags": {"$exists":false}}, {"tags":""}]})
{ "_id" : ObjectId("56670b3072f096ee05a72063"), "abc" : null }
As you can see they all work, although the last query is the most thorough way of testing.
EDIT OP CHANGED QUESTION
You cannot find all values when you type null. That is a value and potential state for a field. You need to do an implicit $and here to get what you want.
db.collection.find({tags:{$exists:true}, tags:{$in:["happy","sad"]}})
How do you actually assemble this in code? Well, that depends on your language, but here is some pseudo code.
def getTags(myTags):
if (tags is None):
db.collection.find({ tags: { "$exists": true } })
else:
db.collection.find({ tags: { "$exists": true }, tags: {"$in": myTags } })
You can also get crafty by using an explicit $and
def getTags(myTags):
query = [{ tags: { "$exists": true } }]
if (tags is Not None):
query.add({tags: {"$in": myTags } })
db.collection.find({ "$and": query })
I hope this answers your question more thoroughly.
The accepted answer isn't suitable for the question(at least nowadays).
In MongoDB >= 3.6.
you can use the $expr operator as follow :
assuming that your parameter name is tagsParam and its value may be an Array or null
db.collections.find({
$or: [
{ $expr: !tagsParam || !tagsParam.length },
{ tags: { $in: paramter } }
]
});
In this case you will get the desired result if the parameter value was ["happy"], null or even an empty array [].