mongoDB search query - mongodb

For an assignment, we are given the following code:
db.bib.insertMany( [
{type : "book",
"#year": "1994",
"title": "TCP/IP Illustrated",
"author": {
"last": "Stevens",
"first": "W."
},
"publisher": "Addison-Wesley",
"price": "65"
},
{type : "book",
"#year": "1992",
"title": "Unix Programming",
"author": {
"last": "Stevens",
"first": "W."
},
"publisher": "Addison-Wesley",
"price": "65"
},
{type : "book",
"#year": "2000",
"title": "Data on the Web",
"author": [
{
"last": "Abiteboul",
"first": "Serge"
},
{
"last": "Buneman",
"first": "Peter"
},
{
"last": "Suciu",
"first": "Dan"
}
],
"publisher": "Morgan Kaufmann",
"price": "39"
},
{type : "book",
"#year": "1999",
"title": "Digital TV",
"editor": {
"last": "Gerbarg",
"first": "Darcy",
"affiliation": "CITI"
},
"publisher": "Kluwer",
"price": "130"
}
,
{type : "journal",
"title": "Irreproducible results",
"editor": {
"last": "Self",
"first": "W."
},
"publisher": "SV"
}
])
Using mongoDB, we are then asked to complete different search queries in order to find the desired information. The one that I am currently stuck on is
List the titles of books published after 1995 and costing less than 100.
From my understanding, the proper query should be something along the lines of
db.bib.find({price: {$lt: 100}, year: {$gt: 1995}}, {title: 1, _id: 0})
However, this provides a blank result when it should not. Why is this and how can I fix it?

Data type for both of the field is string. you can not compare them as numeric. Try following and it will work. using collation, you can ask MongoDB to treat them as int. you can read more about collation here at mongodb.com.
db.bib.find({$and: [{"#year": {$gt: "1995"}}, {price: {$lt: "100"}}]}).collation({
locale: "en_US",
numericOrdering: true
});

Related

I want filter by where on mongodbcollection. Below is my collection entry in db, I want data filtered by companyId, GeoLevelName and GeoLevelValue?

Below is my collection that have hierarchical data stored in it. I want to add filter on GeoLevelValue which stores city names.
{
"_id": {
"$oid": "621cdce8b876f1ec17b1cec9"
},
"CompanyID": "620d2d9efc8cec9c94f26284",
"GeoLevelName": "State",
"IsActive": 1,
"CreatedUser": "string",
"CreatedDate": "2022-02-28T14:27:05.757Z",
"LastModifiedDate": "2022-02-28T14:27:05.757Z",
"LastModifyUser": "string",
"GeoLevelMain": [{
"CompanyId": "620d2d9efc8cec9c94f26284",
"GeoLevelID": "620d2d9efc8cec9c94f26284",
"GeoLevelValue": "Pune"
},{
"CompanyId": "620d2d9efc8cec9c94f26284",
"GeoLevelID": "620d2d9efc8cec9c94f26284",
"GeoLevelValue": "Surat"
}
],
"GeographyID": "621cde14b876f1ec17b1cece",
"DBID": "620f658d6dee6848caf53831",
"DivisionId": "6215d68d9e4786b2f7ab80a0",
"DivisionName": "DivisionName"
}

How to update specific field in mongoDB given conditions?

Given the following mongdoDB structure, how can i update the field isAvailable to false given that the shopName is "jamrt" and slug is "67626dae-1537-40d8-837d-483e5759ada0". This is my query but it does not work: Shop.find({ shopName: shopName}).update({products: {$elemMatch: {slug: slug}}}, { $set: { isAvailable: req.body.isAvailable} } Thanks!
"shopName": "jmart",
"products": [{
"id": 1,
"name": "Clean and Clear Deep Clean Cleanser 100g",
"slug": "8d1c895c-6911-4fc8-a34c-89c6948233d7",
"price": 4.5,
"discount_price": 0,
"category": "Health and Beauty",
"sale": false,
"subcategory": "personal care",
"color": "black",
"article": "Clean and Clear",
"quantity": 9,
"img": "https://firebasestorage.googleapis.com/v0/b/swifty-products.appspot.com/o/Jmart%2FBeauty%2FClean%20and%20Clear%20Deep%20Clean%20Cleanser%20100g.jpg?alt=media",
"vendor": {
"id": 1,
"name": "Clean and Clear"
},
"ratings": {
"star_ratings": 0,
"votes": 0
},
"isAvailable": true
}, {
"id": 2,
"name": "Colgate Total Pro Breath Health",
"slug": "67626dae-1537-40d8-837d-483e5759ada0",
"price": 4.5,
"discount_price": 0,
"category": "Health and Beauty",
"sale": false,
"subcategory": "personal care",
"color": "black",
"article": "Colgate",
"quantity": 9,
"img": "https://firebasestorage.googleapis.com/v0/b/swifty-products.appspot.com/o/Jmart%2FBeauty%2FColgate%20Total%20Pro%20Breath%20Health.jpg?alt=media",
"vendor": {
"id": 2,
"name": "Colgate"
},
"ratings": {
"star_ratings": 0,
"votes": 0
},
"isAvailable": true
},
]
In your case, you are trying to update only the matching sub documents.
The $elemMatch operator while using in projection updates only the first matching sub document.
The $elemMatch operator while using in find updates all the fields of the matching document.
This solution might help you.
With your case, the solution might be the below in mongodb query:
db.Shop.update({"shopName":"jmart","products.slug":"67626dae-1537-40d8-837d-483e5759ada0"}, {$set: {“products.$[i].isAvailable”: false}}, {arrayFilters: [{“i.slug”: "67626dae-1537-40d8-837d-483e5759ada0"}]})

How to do I search in mongoDB? (I want to pull up low level data)

First of all, I don't know correct keyword that I want a feature
So, I write this question.
I want to pull up data depth in mongodb
Can I pull up this?
My NoSql Query is below
db.test.find({
InsertedDate: {
$gt: ISODate("2020-11-09T00:00:00.000Z"),
$lt: ISODate("2020-11-09T12:00:00.000Z")
}
}, {
"HttpDetail.Body": true,
"HttpDetail.QueryString": true,
"HttpDetail.UserId": true,
"InsertedDate": true
})
.limit(3)
.sort({InsertedDate: -1});
I update my original document.
[
{
"_id": {"$oid": "5fa92f269f98260ff81a7aaf"},
"InsertedDate": {"$date": "2020-11-09T11:59:34.951Z"}
},
{
"_id": {"$oid": "5fa92f269f98260ff81a7aae"},
"InsertedDate": {"$date": "2020-11-09T11:59:34.950Z"},
"HttpDetail": {
"QueryString": "",
"Body": "",
"UserId": 103992
}
},
{
"_id": {"$oid": "5fa92f095660dd0d34eb1fd0"},
"InsertedDate": {"$date": "2020-11-09T11:59:05.844Z"},
"HttpDetail": {
"QueryString": "",
"Body": "",
"UserId": 103992
}
}
]
(My Expectation is below)
[
{
"_id": {"$oid": "5fa92f269f98260ff81a7aaf"},
"InsertedDate": {"$date": "2020-11-09T11:59:34.951Z"}
},
{
"_id": {"$oid": "5fa92f269f98260ff81a7aae"},
"InsertedDate": {"$date": "2020-11-09T11:59:34.950Z"},
"Body": "",
"HttpDetail": {
"QueryString": "",
"UserId": 103992
}
},
{
"_id": {"$oid": "5fa92f095660dd0d34eb1fd0"},
"InsertedDate": {"$date": "2020-11-09T11:59:05.844Z"},
"Body": "",
"HttpDetail": {
"QueryString": "",
"UserId": 103992
}
}
]
I can't find it all day long, so I write a question like this.
I can't even think of a keyword to look up.

Query in Embedded document

I want to do a query where i can reach all banks where bank is banco1 and investments are not equal to "box".
How can i do that? I tried this query, but don't work :
db.banks.find( { "investments": { $elemMatch: { bank: "banco1", productName: {$ne:"box} } } } );
This query it's one example of many that i have tried.
Thanks.
{
"_id": "5d3fc8c3914297c7b9a3a9e5",
"banco": "banco 1",
"investimentos": [{
"bank": "banco1",
"risk": "Conservador",
"expiryDate": "2021-10-04",
"tax": "1.02",
"discriminator": "investment",
"productName": "LCI"
},
{
"bank": "banco1",
"risk": "Conservador",
"expiryDate": "2020-06-24",
"tax": "0.75",
"discriminator": "investment",
"productName": "Fundo DI"
},
{
"bank": "banco1",
"risk": "Conservador",
"tax": "0.04",
"discriminator": "investment",
"id": "259ad8ac-57b7-4d33-8e75-46cf5c5c28e3",
"aniversary": "30",
"productName": "box"
}
}],
{
"_id": "5d3fcb4c914297c7b9a3a9e6",
"banco": "banco2",
"investimentos": [{
"bank": "banco2",
"risk": "Conservador",
"expiryDate": "2020-06-24",
"tax": "0.80",
"discriminator": "investment",
"id": "73db503f-c780-448c-a6a8-05d2837ff6ff",
"redemptionDate": "D+1",
"productName": "Fundo DI"
}
,
{
"bank": "banco2",
"risk": "Conservador",
"expiryDate": "2020-12-17",
"tax": "0.98",
"discriminator": "investment",
"id": "54e01515-dc7f-470f-8f00-8603c8f00686",
"productName": "LCA"
},
{
"bank": "banco2",
"risk": "Conservador",
"expiryDate": "2021-08-05",
"tax": "1.0",
"discriminator": "investment",
"id": "259ad8ac-57b7-4d33-8e75-46cf5c5c28e2",
"productName": "CDB"
}
}]
Welcome to SO Luan!
I've found that Mongo Aggregations give me all of the power available in find, and so much more functionality. So about 95% of the time, unless I'm doing a quick query, I end up going to aggregates.
The following aggregate will get you what you're looking for:
db.getCollection('Test').aggregate([
{ $unwind: "$investimentos"},
{ $match: {
'investimentos.bank': "banco1",
'investimentos.productName': /^(?!box$)/
}},
])
The $unwind pipeline takes the array of embedded documents in investimentos, and creates a new document, retaining the parent fields (_id and banco), for each element withing investimentos. You can try just db.getCollection('Test').aggregate([{ $unwind: "$investimentos"}]) to visually see what happens.
The $match pipeline does the same thing as the find method - you give it a list of filters to apply. The second element uses a regex (surrounded by '/' chars) to specify that it should find everything that does not start with "box".

update or replace the mongoose nested array object

I have a timesheet schema which results as below and I want to replace single data array object by a new set of values in mongoose. Either i want remove already existing object and push a new set of values or update the old object with new values.Please suggest me a proper way to achieve this. I am was struggled a lot to do this, because i am new to mongoose and mongodb. Thanks in advance
{
"_id": ObjectId("53f1fb3401ea96440d62646b"),
"user_id": "andrew",
"type": "Solutions",
"timesheets": [{
"weekStartDate": ISODate("2014-08-18T00:00:00Z"),
"weekEndDate": ISODate("2014-08-22T00:00:00Z"),
"_id": ObjectId("53f1fb3401ea96440d62646c"),
"data": [{
"date": ISODate("2014-08-18T00:00:00Z"),
"_id": ObjectId("53f1fb3401ea96440d62646d"),
"record": [{
"_id": ObjectId("53f1fb3401ea96440d626470"),
"desc": "",
"cellId": "0:0",
"custName": "Coach",
"custID": "2",
"timeSpend": "04:00",
"categoryName": "Billing",
"categoryID": "1"
}, {
"_id": ObjectId("53f1fb3401ea96440d62646f"),
"desc": "Description",
"cellId": "0:1",
"custName": "",
"custID": "",
"timeSpend": "05:00",
"categoryName": "Solution",
"categoryID": "4"
}, {
"_id": ObjectId("53f1fb3401ea96440d62646e"),
"desc": "Description",
"cellId": "0:2",
"custName": "",
"custID": "",
"timeSpend": "06:00",
"categoryName": "GTM",
"categoryID": "3"
}],
"savedFlag": false,
"submitFlag": false
}, {
"date": ISODate("2014-08-19T00:00:00Z"),
"_id": ObjectId("53f1fb4e01ea96440d626471"),
"record": [{
"_id": ObjectId("53f1fb4e01ea96440d626474"),
"desc": "",
"cellId": "1:0",
"custName": "Morgan",
"custID": "3",
"timeSpend": "04:00",
"categoryName": "RFP",
"categoryID": "2"
}, {
"_id": ObjectId("53f1fb4e01ea96440d626473"),
"desc": "",
"cellId": "1:1",
"custName": "Morgan",
"custID": "3",
"timeSpend": "05:00",
"categoryName": "RFP",
"categoryID": "2"
}, {
"_id": ObjectId("53f1fb4e01ea96440d626472"),
"desc": "",
"cellId": "1:2",
"custName": "Citi",
"custID": "1",
"timeSpend": "04:00",
"categoryName": "Sales",
"categoryID": "0"
}],
"savedFlag": false,
"submitFlag": false
}],
"savedFlag": true,
"submitFlag": false
}],
"__v": 0
} >