I am trying below queries to get the output which has start_date greater than current date.
These in structure of my collection:
{
"_id" : ObjectId("5aeac6cd1b7e6f252832ca0e"),
"recruiter_id" : null,
"university_id" : null,
"type" : "quiz",
"name" : "Enter scheduled quiz without end date",
"description" : "Even after detailed market research, some products just don't work in the market. Here's a case study from the Coca-Cola range. ",
"quizpoll_image" : "story_7.jpeg",
"status" : "1",
"quizpoll_type" : "scheduled",
"duration" : {
"duration_type" : "Question wise",
"total_duration" : "1000"
},
"questions" : [
{
"question_id" : "5aeaa4021b7e6f00dc80c5c6"
},
{
"question_id" : "5aeaa59d1b7e6f00dc80c5d2"
}
],
"date_type" : {
"start_date" : ISODate("2018-05-01T00:00:00.000+0000")
},
"created_at" : ISODate("2018-05-01T00:00:00.000+0000"),
"updated_at" : ISODate("2018-04-26T07:58:17.795+0000")
}
This the query I am trying :
var isoCurrentDate = current_date.toISOString();
var quizScheduledData = await QuizListingCollection.find({
where: ({
'type':'quiz',
'status':'1',
'quizpoll_type':'scheduled',
'date_type' :{
'start_date':{
'>': isoCurrentDate
}
}
})
});
This is the error I get when I hit this api in postman
{
"cause": {
"name": "UsageError",
"code": "E_INVALID_CRITERIA",
"details": "Could not use the provided `where` clause. Could not filter by `date_type`: Unrecognized modifier (`start_date`) within provided constraint for `date_type`."
},
"isOperational": true,
"code": "E_INVALID_CRITERIA",
"details": "Could not use the provided `where` clause. Could not filter by `date_type`: Unrecognized modifier (`start_date`) within provided constraint for `date_type`."
}
{
where: {
'type':'quiz',
'status':'1',
'quizpoll_type':'scheduled',
'date_type.start_date': {
'>' : isoCurrentDate
}
}
}
Related
I have updateMany function as follows
Article.updateMany({author: userId}, {author: anonym}, function(err, updated) {
if (err) {
res.send(err);
} else {
res.send(updated);
}
});
userId is = 6068b57dbe4eef0b579120c7
anonym is = 6069870676d6320f39e7e5a2
for testing purposes I have a single article in MongoDB as follows
db.articles.find()
{ "_id" : ObjectId("6068b591be4eef0b579120c8"), "favoritesCount" : 1, "comments" : [ ], "tagList" : [ ], "title" : "Martin", "description" : "Testib", "body" : "Asju", "author" : ObjectId("6068b57dbe4eef0b579120c7"), "slug" : "martin-2hzx78", "createdAt" : ISODate("2021-04-03T18:36:01.977Z"), "updatedAt" : ISODate("2021-04-03T18:53:29.809Z"), "__v" : 0 }
You can see that article has "author" : id field in it which currently shows userId as author.
I want to update that field and transfer authorship to anonym user.
When I send this request to postman I get following response
{
"n": 0,
"nModified": 0,
"ok": 1
}
And database remains unchanged. What am I doing wrong here ?
using a "now" in my range query as shown below
"range":{
"metadata_fields.time_start":{
"lte":"now",
"gt":"now-7d"
}
}
results in an error as shown below
{
"error" : {
"root_cause" : [
{
"type" : "parse_exception",
"reason" : "could not read the current timestamp"
}
],
"type" : "search_phase_execution_exception",
"reason" : "all shards failed",
"phase" : "query",
"grouped" : true,
"failed_shards" : [
{
"shard" : 0,
"index" : "memsnippet_idx_1.1",
"node" : "XDHi_2BbSQGb33IHDasxfA",
"reason" : {
"type" : "parse_exception",
"reason" : "could not read the current timestamp",
"caused_by" : {
"type" : "illegal_argument_exception",
"reason" : "features that prevent cachability are disabled on this context"
}
}
}
]
},
"status" : 400
}
I upgraded to 7.11 today, my index.requests.cache.enable is true. Not sure why ES cannot read the current date?
edit 1:
"aggregations":{
"named_entities":{
"significant_terms":{
"gnd":{
"background_is_superset":false
},
"field":"predicted_fields.named_entities.display.keyword",
"size":10000,
"background_filter":{
"bool":{
"filter":[
{
"match":{
"owner_id":{
"query":8,
"operator":"and"
}
}
},
{
"range":{
"metadata_fields.time_start":{
"lte":"now-7d"
}
}
}
],
"should":[
],
"must":[
]
}
}
}
}
}
This is my significant aggregations query that is not working, "now" works in a range query when filtering but not in this aggregations.
I have documents in which I would like to update the hostUser with one of the members of the document,also have to delete the record from the member document and add the chips of the deleted member in the club chips.
Here is the sample document.
{
"_id" : "1002",
"hostUser" : "1111111111",
"clubChips" : 10000,
"requests" : {},
"profile" : {
"clubname" : "AAAAA",
"image" : "0"
},
"tables" : [
"SJCA3S0Wm"
],
"isDeleted" : false,
"members" : {
"1111111111" : {
"chips" : 0,
"id" : "1111111111"
},
"2222222222" : {
"chips" : 0,
"id" : "2222222222"
}
}
}
This is what I have tried.
db.getCollection('test').updateMany({"hostUser":"1111111111"},
{"$set":{"hostUser":"2222222222"},"$unset":{"members.1111111111":""}})
This is how you would handle unset and set in a single call to updateMany. Can you please clarify what you meant by "check if the values exist in the member field"?
db.getCollection('test').updateMany(
{"hostUser":"1111111111"},
{
'$set': {"hostUser":"2222222222"} ,
'$unset': {"members.1111111111":""}
}
)
I have a number of documents in my database where I am applying document validation. All of these documents may have embedded documents. I can apply simple validation along the lines of SQL non NULL checks (these are essentially enforcing the primary key constraints) but what I would like to do is apply some sort of conditional validation to the optional arrays and embedded documents. By example, lets say I have a document that looks like this:
{
"date": <<insertion date>>,
"name" : <<the portfolio name>>,
"assets" : << amount of money we have to trade with>>
}
Clearly I can put validation on this document to ensure that date name and assets all exist at insertion time. Lets say, however, that I'm managing a stock portfolio and the document can have future updates to show an array of stocks like this:
{
"date" : <<insertion date>>,
"name" : <<the portfolio name>>,
"assets" : << amount of money we have to trade with>>
"portfolio" : [
{ "stockName" : "IBM",
"pricePaid" : 155.39,
"sharesHeld" : 100
},
{ "stockName" : "Microsoft",
"pricePaid" : 57.22,
"sharesHeld" : 250
}
]
}
Is it possible to to apply a conditional validation to this array of sub documents? It's valid for the portfolio to not be there but if it is each document in the array must contain the three fields "stockName", "pricePaid" and "sharesHeld".
MongoShell
db.createCollection("collectionname",
{
validator: {
$or: [
{
"portfolio": {
$exists: false
}
},
{
$and: [
{
"portfolio": {
$exists: true
}
},
{
"portfolio.stockName": {
$type: "string",
$exists: true
}
},
{
"portfolio.pricePaid": {
$type: "double",
$exists: true
}
},
{
"portfolio.sharesHeld": {
$type: "double",
$exists: true
}
}
]
}
]
}
})
With this above validation in place you can insert documents with or without portfolio.
After executing the validator in shell, then you can insert data of following
db.collectionname.insert({
"_id" : ObjectId("58061aac8812662c9ae1b479"),
"date" : ISODate("2016-10-18T12:50:52.372Z"),
"name" : "B",
"assets" : 200
})
db.collectionname.insert({
"_id" : ObjectId("58061ab48812662c9ae1b47a"),
"date" : ISODate("2016-10-18T12:51:00.747Z"),
"name" : "A",
"assets" : 100,
"portfolio" : [
{
"stockName" : "Microsoft",
"pricePaid" : 57.22,
"sharesHeld" : 250
}
]
})
If we try to insert a document like this
db.collectionname.insert({
"date" : new Date(),
"name" : "A",
"assets" : 100,
"portfolio" : [
{ "stockName" : "IBM",
"sharesHeld" : 100
}
]
})
then we will get the below error message
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
Using Mongoose
Yes it can be done, Based on your scenario you may need to initialize the parent and the child schema.
Shown below would be a sample of child(portfolio) schema in mongoose.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var portfolioSchema = new Schema({
"stockName" : { type : String, required : true },
"pricePaid" : { type : Number, required : true },
"sharesHeld" : { type : Number, required : true },
}
References:
http://mongoosejs.com/docs/guide.html
http://mongoosejs.com/docs/subdocs.html
Can I require an attribute to be set in a mongodb collection? (not null)
Hope it Helps!
I'm pretty new with monogodb and I'm trying to use the aggregation framework to get the sum of revenue for each agent.
My data looks like this:
{
"_id" : ObjectId("56ce2ce5b69c4a909eb50f22"),
"property_id" : 5594,
"reservation_id" : "3110414.1",
"arrival" : "2016-02-24",
"los" : 1,
"updated" : ISODate("2016-02-24T22:21:27.000Z"),
"offer_list" : {
"68801" : {
"pitched" : "yes",
"accepted" : "yes",
"prime_price" : "3",
"agent_price" : "",
"price_per" : "night"
},
"63839" : {
"pitched" : "yes",
"accepted" : "yes",
"prime_price" : "8",
"agent_price" : "",
"price_per" : "night"
}
},
"status" : "accepted",
"comments" : [],
"created" : ISODate("2016-02-24T22:21:18.000Z"),
"agent_id" : 50941
}
For each agent_id, I would like to get the sum of all "agent_price" (or "prime_price" if "agent_price" is None) multiplied by field "los" when "accepted"=="yes".
For the example above the expected output would be:
{'sum':11, 'agent_id": 50941}
The sum is the two "accepted" "prime_price" (8+3) times los (1) = 11.
I tried to use $unwind but it only works for a list, not object. Can anyone help on that?
I doubt it is possible with aggregation, yet should be straightforward with mapreduce:
db.collection.mapReduce(
function(){
for(key in this.offer_list) {
if (this.offer_list[key].accepted == 'yes') {
if (this.offer_list[key].agent_price == '') {
emit(this.agent_id, this.los * this.offer_list[key].prime_price);
} else {
emit(this.agent_id, this.los * this.offer_list[key].agent_price);
}
]
}
},
function(agent, values) {
return Array.sum(values);
}
)
For real-life code, I would also add a query option for data sanitation.