用数组在MongoDB中查找值 [英] Find values in mongodb with array

查看:129
本文介绍了用数组在MongoDB中查找值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个mongodb表中获取值,这个表存储着一个商店(日期存储为字符串)和python中的股票数据。



存储在表中的数据:

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

我想找到两天所需产品的名称 28-9-2015& 29-9-2015



现在每个人都这样做



<$ p $ {$> $ $ $ $ $ $ $ $ $ db.stockdate.find({RequiredDate:29-9-2015 })

我可以在单个查询中执行这些操作吗?
像在单个查询中给出两个日期,并得到与两个查询相同的结果。

解决方案

使用 $ in

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

就像产品的名称一样,您可以使用

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

如果您想根据日期对记录进行分组,您将需要使用聚合:

  db.stockdate。汇总([
{$ match:{RequiredDate:{$ in:[28-9-2015,29-9-2015]}},
{$ group:{ _id:RequiredDate,名称:{$ push:$ Name},count:{$ sum:1}}}
])

上面的聚合查询会产生像这样的结果:

  {
_id:28-9-2015,
姓名:[xyz],
count:1
}
{
_id:29-9-2015,
名称:[abc,def],
count:2
}

您可以添加尽可能多的日期到数组,这将返回reuiredDate设置为任何日期的记录。


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.

解决方案

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.

这篇关于用数组在MongoDB中查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆