1

I am trying to get values from a mongodb table which stores data about stock taking dates in a shop(the date is stored as string) along with python.

the data stored in the table:

{
    "_id" : ObjectId("5645f0443f32df13e0dc786e"),
    "RequiredDate" : "28-9-2015",
    "Name": "xyz"
}
{
    "_id" : ObjectId("5645f0c73f32df062064a0f6"),
    "RequiredDate" : "29-9-2015",
    "Name": "abc"
}

I would like to find the name of the products which are required on both days 28-9-2015 & 29-9-2015.

Right now do it individually like this

db.stockdate.find({"RequiredDate": "28-9-2015"})
db.stockdate.find({"RequiredDate": "29-9-2015"})

Can i do these in a single query, Is there any option for that? like giving both date in a single query and get the same result which i got with two query.

1 Answer 1

1

Use the $in operator.

db.stockdate.find({"RequiredDate": {$in: ["28-9-2015", "29-9-2015"]}})

Additionally, if you'd just like the names of the products, you can use

db.stockdate.distinct("Name", {"RequiredDate": {$in: ["28-9-2015", "29-9-2015"]}})

If you want to group the records based on the dates, you will need to use aggregation:

db.stockdate.aggregate([
    {$match: {"RequiredDate": {$in: ["28-9-2015", "29-9-2015"]}}},
    {$group: {_id: "RequiredDate", Names: {$push: "$Name"}, count: {$sum: 1}}}
])

The above aggregation query will produce a result like this:

{
    "_id" : "28-9-2015",
    "Names": ["xyz"],
    "count": 1
}
{
    "_id" : "29-9-2015",
    "Names": ["abc", "def"],
    "count": 2
}

You can add as many dates to the array, and this will return records that have the reuiredDate set to any of those dates.

Sign up to request clarification or add additional context in comments.

2 Comments

There might me multiple results for the above query with(multiple dates) is there a way to know which date has stock taking so that i can give a total count of all the products that they are stock taking?
Okay. For that you will need to use aggregation. Gimme a minute for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.