I'm new to mongo and need help finding db entries created at requested time. In my example there are a lot of embedded fields, and I do not understand syntaxis for request:
{
"_id": "54e1a045e4b03f5930293da6",
"_version": 31867,
"_transId": "4ae4d0e6-d3df-4a24-9621-1cdb7f12362f-10489329",
"accountBalances": {
"BALANCE": {
"thresholds": {
},
"quotas": "ROLLOVER_QUOTA": {
"thresholds": {
},
"quotaCode": "ROLLOVER_QUOTA",
"credits": {
"_1HVa0dJoEeSUwbM1-xYKvg": {
"startDate": ISODate("2015-03-24T21:00:00Z"),
"creditAmount": "547194099151",
"endDate": ISODate("2020-03-24T21:00:00Z"),
"started": true,
"debits": {
"consolidated": {
"creationDate": ISODate("2015-04-17T18:00:01.469Z"),
"debitAmount": "547194090291",
"debitId": "consolidated"
}
},
"creditId": "_1HVa0dJoEeSUwbM1-xYKvg"
}
}
}
}
}
I need to search for entries which have debit creation date $gte:ISODate("2015-03-16T00:00:00.000Z"), $lte:ISODate("2015-03-16T04:00:00.000Z"
You can use the dot notation to access the fields of an embedded document:
db.collection.find(
{
"accountBalances.BALANCE.quotas.ROLLOVER_QUOTA.credits._1HVa0dJoEeSUwbM1-xYKvg.debits.creationDate": {
"$gte": ISODate("2015-03-16T00:00:00.000Z"),
"$lte": ISODate("2015-03-16T04:00:00.000Z")
}
}
);
Related
In the database, I have documents like the following
Ticket {
"eventHistory": [
{
"event": "CREATED",
"timestamp": "aa-bb-cccc"
},
{
"event": "ASSIGNED",
"timestamp": "ii-jj-kkkk"
},
...
{
"event": "CLOSED",
"timestamp": "xx-yy-zzzz"
}
]
}
I would like to add a closedAt field to the relevant Tickets, getting the value from the eventHistory array's last element. The resultant document would look like the following
Ticket {
"eventHistory": [
{
"event": "CREATED",
"timestamp": "aa-bb-cccc"
},
{
"event": "ASSIGNED",
"timestamp": "ii-jj-kkkk"
},
...
{
"event": "CLOSED",
"timestamp": "xx-yy-zzzz"
}
],
"closedAt": "xx-yy-zzzz"
}
The following pipeline allows me to use the entire object that's present as the eventHistory array's last element.
db.collection.updateMany(
<query>,
[
"$set": {
"closedAt": {
"$arrayElemAt": [
"$eventHistory",
-1
]
}
}
]
...
)
But I want to use only the timestamp field; not the entire object.
Please help me adjust (and/or improve) the pipeline.
One option to fix your query is:
db.collection.updateMany(
<query>,
[
{
$set: {
"Ticket.closedAt": {
$last: "$Ticket.eventHistory.timestamp"
}
}
}
])
See how it works on the playground example
But note that you assume that last item is a closing one. Is this necessarily the case? Otherwise you can validate it.
I have the following mongo db schema and I am trying to build an aggregate query that searches under github_open_issues under the repo key and can return me a match for all the values with repoA as the value. I have tried the following as my query however its not returning any result. Im a bit confused why this is not working as I have another db with a schema similar to this and this type of query works there but here something seems to be different and is not working. I have also put together this interactive example mongoplayground
query
db.collection.aggregate([
{
"$unwind": "$github_open_issues"
},
{
"$match": {
"github_open_issues.repo": {
"$in": [
"repoA"
]
}
}
},
])
schema
[
{
"github_open_issues": {
"0": {
"git_url": "https://github.com/",
"git_assignees": "None",
"git_open_date": "2019-09-26",
"git_id": 253113,
"repo": "repoA",
"git_user": "userA",
"state": "open"
},
"1": {
"git_url": "https://github.com/",
"git_assignees": "None",
"git_open_date": "2019-11-15",
"git_id": 294398,
"repo": "repoB",
"git_user": "userB",
"state": "open"
},
"2": {
"git_url": "https://github.com/",
"git_assignees": "None",
"git_open_date": "2021-04-12",
"git_id": 661208,
"repo": "repoA",
"state": "open"
}
},
"unique_label_seen": {
"568": {
"label_name": "some label",
"times_seen": 12,
"535": {
"label_name": "another label",
"times_seen": 1
}
}
}
}
]
$objectToArray convert github_open_issues object to array in key-value format
$filter to iterate loop of above converted array and filter your search condition
$match to filter github_open_issues not empty
$arrayToObject convert github_open_issues array to object
db.collection.aggregate([
{
$addFields: {
github_open_issues: {
$filter: {
input: { $objectToArray: "$github_open_issues" },
cond: { $in: ["$$this.v.repo", ["repoA"]] }
}
}
}
},
{ $match: { github_open_issues: { $ne: [] } } },
{ $addFields: { github_open_issues: { $arrayToObject: "$github_open_issues" } } }
])
Playground
You query is correct but you data in schema placed wrong inside github_open_issues.repo your objects are place by numbers like {"0": {values... }, "1":{values... }} which cannot get your desired value. You can check the playground now playground
I've got a problem with mongo query. I want to take all the data in given time. eg. From 2019-01-01 to 2019-01-10. But I see that if even one element matches the condition mongo is returning me whole data.
db.production.aggregate([
{
"$group": {
"_id": "$machine_name",
"array": {
"$push": {
"value": "$value",
"type": "$variable_name",
"date": {
"$dateFromString": {
"dateString": "$datetime_from",
"format": "%Y-%m-%d %H:%M:%S"
}
}
}
}
}
},
{
"$match": {
"$and": [
{
"array.date": {
"$gt": ISODate("2019-01-01T00:00:00Z")
}
},
{
"array.date": {
"$lt":ISODate("2019-01-02T23:59:59Z")
}
}
]
}
}
]);
Here is schema:
It should return only data in a given time period
Project the data you want to view. For example in when we use find query
db.collectionname.find({
fieldname: "value"
},
{
fieldname: 1
})
So , here first {} matches and second {} projects only that value.
Depending on your schema if there are conditions if this value is present in some documents not in other the use conditions like "fieldname":{ $exists: true}} in match condition.
I've a problem with a huge MongoDb aggregation pipeline. I've many constraint and I've simplified the problem a lot. Hence, don't discuss the goal for this query.
I've a mongo aggregation that gives something similar to this:
[
{
"content": {
"processes": [
{
"id": "101a",
"title": "delivery"
},
{
"id": "101b",
"title": "feedback"
}
]
}
}
]
To this intermediate result I'm forced to apply a project operation in order to obtain something similar to this:
[
{
"results":
{
"titles": [
{
"id": "101a",
"value": "delivery"
},
{
"id": "101b",
"value": "feedback"
}
]
}
}
]
enter code here
But applying this projections:
"results.titles.id": "$content.processes.id",
"results.titles.value": "$content.processes.title"
I obtain this:
[
{
"results":
{
"titles": {
"id": ["101a", "101b"]
"value": ["delivery", "feedback"]
}
}
}
}
]
Collection are created but not in the proper position.
Is it possible to exploit some operator inside the project operation in order to tell mongo to create an array in a parent position?
Something like this:
"results.titles.$[x].value" : "$content.processes.value"
You can use the dot notation to project entire array:
db.col.aggregate([
{
$project: {
"results.titles": "$content.processes"
}
}
])
and if you need to rename title to value then you have to apply $map operator:
db.col.aggregate([
{
$project: {
"results.titles": {
$map: {
input: "$content.processes",
as: "process",
in: {
id: "$$process.id",
value: "$$process.title"
}
}
}
}
}
])
I'm trying to mass update some mongo documents.
I'm using the query
db.articles.update(
{
'categories.id': ObjectId("51cd5272222wb6zs464fa4d9"),
'source.importer': 'pa'
},
{
$set :
{
'source.expires-at': ISODate("2014-01-01T08:39:45Z")
}
}
)
This query does not update the source.expires-at field, however the where part of the statement works fine.
The document structure is
{
"_id": ObjectId("5211dc100000044707000015"),
"categories": {
"0": {
"id": ObjectId("51cd5272222wb6zs464fa4d9")
}
},
"source": {
"importer": "pa",
"expires-at": ISODate("2013-09-18T08:49:32.0Z")
}
}
Try this:
db.articles.update(
{
'categories.id': ObjectId("51cd5272222wb6zs464fa4d9"),
'source.importer': 'pa'
},
{
$set: {
'source.expires-at': ISODate("2014-01-01T08:39:45Z")
}
},
{ multi: true }
)
You will need to pass additional option argument {multi: true};
Look in to this https://education.10gen.com/courses/10gen/M101JS/2013_August/courseware/CRUD/Multi-update/