How to query neighbor elements in MongoDB? - javascript

I am implementing a ranking system. I have a collection with elements like this:
{"_id" : 1, "count" : 32}
{"_id" : 2, "count" : 12}
{"_id" : 3, "count" : 34}
{"_id" : 4, "count" : 9}
{"_id" : 5, "count" : 77}
{"_id" : 6, "count" : 20}
I want to write a query that return an element which has {"id" : 1} and 2 other neighbor elements (after sorting by count). Totally 3 elements returned.
Ex:
After sorting:
9 12 20 32 34 77
The query should return 20 32 34.

You will never get this in a single query operation, but it can be obtained with "three" queries. The first to obtain the value for "count" from the desired element, and the subsequent ones to find the "preceding" and "following" values.
var result = [];
var obj = db.collection.findOne({ "_id": 1 }); // returns object as selected
result.push(obj);
// Preceding
result.unshift(db.collection.findOne({
"$query": { "count": { "$lt": obj.count } },
"$orderby": { "count": -1 }
}));
// Following
result.push(db.collection.findOne({
"$query": { "count": { "$gt": obj.count } },
"$orderby": { "count": 1 }
}));
Asking to do this in a "single query" is essentially asking for a "join", which is something that MongoDB essentially does not do. It is a "Set Intersection" of the discrete results, and that in SQL is basically a "join" operation.

Related

How to pull nested document from the array of documents in mongodb?

I am trying to remove a nested objects array in my document. The scenario is that i am searching for the days an event will be organised for, by using its eventid
const { eventid, typesOfTicketId } = req.params;
const eventDays = await EventDate.find({event: eventid});
Here eventid is passed from params as "5e9c0f0593ab3c058e282bfa". I then want to remove a requested day from the nested objects array. From the above query, I am receiving an array of dates and on each index of array the document is in this format:
[{
"_id" : ObjectId("5ea7f54b8b22480431f1a455"),
"day" : "1588186800",
"typesOfTicket" : [
{
"_id" : ObjectId("5ea7f54b8b22480431f1a456"),
"ticket" : "Adult Tickets",
"noTickets" : 40,
"price" : 50,
"ticketsLeft" : 40
},
{
"_id" : ObjectId("5ea7f54b8b22480431f1a457"),
"ticket" : "Children Tickets",
"noTickets" : 50,
"price" : 30,
"ticketsLeft" : 50
}
],
"event" : ObjectId("5e9c0f0593ab3c058e282bfa"),
"__v" : 0
},
{
"_id" : ObjectId("5ea7f5678b22480431f1a45f"),
"day" : "1588273200",
"typesOfTicket" : [
{
"_id" : ObjectId("5ea7f5678b22480431f1a460"),
"ticket" : "Male Tickets",
"noTickets" : 50,
"price" : 5,
"ticketsLeft" : 50
},
{
"_id" : ObjectId("5ea7f5678b22480431f1a461"),
"ticket" : "Female Tickets",
"noTickets" : 50,
"price" : 5,
"ticketsLeft" : 50
}
],
"event" : ObjectId("5e9c0f0593ab3c058e282bfa"),
"__v" : 0
}]
What i want is to find a way to remove the document in the nested typesOfTicket array, like lets say i want to remove the Object with id: typesOfTicketId. (e.g typesOfTicketId = "5ea7f5678b22480431f1a461"), the female ticket one by passing its ID.
I have already tried this query:
await EventDate.update({event: eventid}, {
$pull: {
typesOfTicket: {
_id: "typesOfTicketIDHERE"
}
}
});
But the above given query is only working if i am removing the first index of eventDays Array, like if i am deleting the ID: "5ea7f54b8b22480431f1a456", then this will work but if i am going for the id's on the second index like "Female tickets"/"5ea7f5678b22480431f1a461", then it is not working.
I found the solution to my problem, the above query did work correctly after just some adjustments
await EventDate.update({event: eventid}, {
$pull: {
typesOfTicket: {
_id: "typesOfTicketIDHERE"
}
}
}, { multi: true });
Just specifying the multi params to true will do the trick.

How to fetch the length of a string and fetch values?

How to fetch the length and individual values in javascript
here is example data
examples:
"numbers": "248001,248142",
"numbers": "588801,248742,588869"
Actuall code
{
"_id" : ObjectId("579ce69f4be1811f797fbab2"),
"city" : "",
"sdescription" : "",
"categories" : [
"5729f312d549cc3212c8393b"
],
"numbers" : "4555855,421201",
"createdAt" : ISODate("2016-07-30T17:40:47.022Z"),
"month" : 7,
"year" : 2016
}
here is my code and error
let num = numbers.split(',')
(node:5628) UnhandledPromiseRejectionWarning: TypeError: numbers.split is not a function
I have tried split to separate the values but some times it returns an error as number.split is not a function.
I want to return two things:
length: in the first example length should be 2 and in the second example
length should be 3.
2.values should get split
You need to call start from object name objectname.keyname
var obj = { "city": "", "sdescription": "", "categories": [ "5729f312d549cc3212c8393b" ], "numbers": "4555855,421201", "month": 7, "year": 2016 }
var res = obj.numbers.split(',').length;
console.log(res)
You can loop through your object and then for each element access numbers property and then split and find length
let json = [{"numbers": "248001,248142"},{"numbers": "588801,248742,588869"},{"numbers":[]}]
json.forEach(({numbers})=>{
console.log(typeof numbers === 'string' ? numbers.split(',').length : 'Not a string')
})

Query to Match on nth Document of an Array

I am new to MongoDB and I am doing some exercises on it. In particular I got stuck on this exercise, of which I report here the question:
Given the following structure for document "Restaurant":
{
"_id" : ObjectId("5704adbc2eb7ebe23f582818"),
"address" : {
"building" : "1007",
"coord" : [
-73.856077,
40.848447
],
"street" : "Morris Park Ave",
"zipcode" : "10462"
},
"borough" : "Bronx",
"cuisine" : "Bakery",
"grades" : [
{
"date" : ISODate("2014-03-03T00:00:00Z"),
"grade" : "A",
"score" : 2
},
{
"date" : ISODate("2013-09-11T00:00:00Z"),
"grade" : "A",
"score" : 6
},
{
"date" : ISODate("2013-01-24T00:00:00Z"),
"grade" : "A",
"score" : 10
},
{
"date" : ISODate("2011-11-23T00:00:00Z"),
"grade" : "A",
"score" : 9
},
{
"date" : ISODate("2011-03-10T00:00:00Z"),
"grade" : "B",
"score" : 14
}
],
"name" : "Morris Park Bake Shop",
"restaurant_id" : "30075445"
}
Write a MongoDB query to find the restaurant Id, name and grades for those restaurants where 2nd element of grades array contains a grade of "A" and score 9 on an ISODate "2014-08-11T00:00:00Z".
I wrote this query:
db.restaurants.find(
{
'grades.1': {
'score': 'A',
'grade': 9,
'date' : ISODate("2014-08-11T00:00:00Z")
}
},
{
restaurant_id: 1,
name: 1,
grades: 1
});
which is not working.
The solution provided is the following:
db.restaurants.find(
{ "grades.1.date": ISODate("2014-08-11T00:00:00Z"),
"grades.1.grade":"A" ,
"grades.1.score" : 9
},
{"restaurant_id" : 1,"name":1,"grades":1}
);
My questions are:
is there a way to write the query avoiding to repeat the grades.1 part?
Why is my query wrong, given that grades.1 is a document object?
If it can help answering my question, I am using MongoDB shell version: 3.2.4
EDIT:
I found an answer to question 2 thanks to this question.
In particular I discovered that order matters. Indeed, if I perform the following query, I get a valid result:
db.restaurants.find({'grades.1': {'date': ISODate("2014-08-11T00:00:00Z"), 'grade':'A', score:9}}, {restaurant_id:1, name:1, grades:1})
Note that this query works only because all subdocument's "fields" are specified, and they are specified in the same order.
Not really. But perhaps an explanation of what you "can" do:
db.junk.find({
"grades": {
"$elemMatch": {
"date" : ISODate("2014-03-03T00:00:00Z"),
"grade" : "A",
"score" : 2
}
},
"$where": function() {
var grade = this.grades[0];
return (
grade.date.valueOf() == ISODate("2014-03-03T00:00:00Z").valueOf() &&
grade.grade === "A" &&
grade.score ==== 2
)
}
})
The $elemMatch allows you to shorten a little, but it is not the "nth" element of the array. In order to narrow that further you need to use the $where clause to inspect the "nth" array element to see if all values are a match.
db.junk.aggregate([
{ "$match": {
"grades": {
"$elemMatch": {
"date" : ISODate("2014-03-03T00:00:00Z"),
"grade" : "A",
"score" : 2
}
}
}},
{ "$redact": {
"$cond": {
"if": {
"$let": {
"vars": { "grade": { "$arrayElemAt": [ "$grades", 0 ] } },
"in": {
"$and": [
{ "$eq": [ "$grade.date", ISODate("2014-03-03T00:00:00Z") ] },
{ "$eq": [ "$grade.grade", "A" ] },
{ "$eq": [ "$grade.score", 2 ] }
]
}
}
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
])
You can do the same logic with $redact as well using .aggregate(). It runs a little quicker, but the basic truth should be clear by now.
So using "dot notation" to specify the "nth" position for each element within the array like you have already done is the most efficient and "brief" way to write this. You cannot make it shorter or better.
Your other attempt is looking for a "document" within "grades.1" that matches exactly the document condition you are providing. If for any reason those are not the only fields present, or if they are indeed in "different order" in the stored document, then such a query condition will not be a match.

Match Documents where all array members do not contain a value

MongoDB selectors become quickly complicated, especially when you come from mySQL using JOIN and other fancy keywords. I did my best to make the title of this question as clear as possible, but failed miserably.
As an example, let a MongoDB collection have the following schema for its documents:
{
_id : int
products : [
{
qte : int
status : string
},
{
qte : int
status : string
},
{
qte : int
status : string
},
...
]
}
I'm trying to run a db.collection.find({ }) query returning documents where all products do not have the string "finished" as status. Please note that the products array has a variable length.
We could also say we want all documents that has at least one product with a status that is not "finished".
If I were to run it as a Javascript loop, we would have something like the following :
// Will contain queried documents
var matches = new Array();
// The documents variable contains all documents of the collection
for (var i = 0, len = documents.length; i < len; i++) {
var match = false;
if (documents[i].products && documents[i].products.length !== 0) {
for (var j = 0; j < documents[i].products; j++) {
if (documents[i].products[j].status !== "finished") {
match = true;
break;
}
}
}
if (match) {
matches.push(documents[i]);
}
}
// The previous snippet was coded directly in the Stack Overflow textarea; I might have done nasty typos.
The matches array would contain the documents I'm looking for. Now, I wish there would be a way of doing something similar to collection.find({"products.$.status" : {"$ne":"finished"}}) but MongoDB hates my face when I do so.
Also, documents that do not have any products need to be ignored, but I already figured this one out with a $and clause. Please note that I need the ENTIRE document to be returned, not just the product array. If a document has products that are not "finished", then the entire document should be present. If a document has all of its products set at "finished", the document is not returned at all.
MongoDB Version: 3.2.4
Example
Let's say we have a collection that contains three documents.
This one would match because one of the status is not "finished".
{
_id : 1,
products : [
{
qte : 10,
status : "finished"
},
{
qte : 21,
status : "ongoing"
},
]
}
This would not match because all statuses are set to "finished"
{
_id : 2,
products : [
{
qte : 35,
status : "finished"
},
{
qte : 210,
status : "finished"
},
{
qte : 2,
status : "finished"
},
]
}
This would also not match because there are no products. It would also not match if the products field was undefined.
{
_id : 3,
products : []
}
Again, if we ran the query in a collection that had the three documents in this example, the output would be:
[
{
_id : 1,
products : [
{
qte : 10,
status : "finished"
},
{
qte : 21,
status : "ongoing"
},
]
}
]
Only the first document gets returned because it has at least one product that doesn't have a status of "finished", but the last two did not make the cut since they either have all their products' statuses set as "finished", or don't have any products at all.
Try following query. It's fetching documents where status is not equals to "finished"
Note: This query will work with MongoDB 3.2+ only
db.collection.aggregate([
{
$project:{
"projectid" : 1,
"campname" : 1,
"campstatus" : 1,
"clientid" : 1,
"paymentreq" : 1,
products:{
$filter:{
input:"$products",
as: "product",
cond:{$ne: ["$$product.status", "finished"]}
}
}
}
},
{
$match:{"products":{$gt: [0, {$size:"products"}]}}
}
])
You need .aggregate() rather than .find() here. That is the only way to determine if ALL elements actually don't contain what you want:
// Sample data
db.products.insertMany([
{ "products": [
{ "qte": 1 },
{ "status": "finished" },
{ "status": "working" }
]},
{ "products": [
{ "qte": 2 },
{ "status": "working" },
{ "status": "other" }
]}
])
Then the aggregate operation with $redact:
db.products.aggregate([
{ "$redact": {
"$cond": {
"if": {
"$anyElementTrue": [
{ "$map": {
"input": "$products",
"as": "product",
"in": {
"$eq": [ "$$product.status", "finshed" ]
}
}}
]
},
"then": "$$PRUNE",
"else": "$$KEEP"
}
}}
])
Or alternately you can use the poorer and slower cousin with $where
db.products.find(function(){
return !this.products.some(function(product){
return product.status == "finished"
})
})
Both return just the one sample document:
{
"_id" : ObjectId("56fb4791ae26432047413455"),
"products" : [
{
"qte" : 2
},
{
"status" : "working"
},
{
"status" : "other"
}
]
}
So the $anyElementTrue with the $map input or the .some() are basically doing the same thing here and evaluating if there was any match at all. You use the "negative" assertion to "exclude" documents that actually find a match.

find length of json name/values pairs

In this code I'm using the 2 name/values pairs in each record
I'm getting the alert with value 4 while I want to search the of numbers of pairs we have that is FirstName,sal so I want the value 2 in alert????
var Newdata = [
{ "FirstName" : "John" , "Sal" : 10 },
{ "FirstName" : "Anna" , "Sal" : 30 },
{ "FirstName" : "Peter" , "Sal" : 30 },
{ "FirstName" : "Hemant" , "Sal" : 30 },];
alert(Newdata.length);
Try to use Object.keys() like,
alert(Object.keys(Newdata[0]).length);
Demo

Categories

Resources