我有以下mongoDB集合数据。我正在尝试使用typesOfExicution,companyName和projectName获取数据。 我写了下面的查询来查找
db.getCollection('SETTINGS').find({'companyName':'VV', 'typesOfExicution' : 'validation', 'automation.projectName' : 'hdh'})
如果我不使用automation.projectName
我能够找到数据。但如果我使用它,那么它将返回0条记录。
那么从数组中查找数据的确切查询是什么。
/* 1 */
{
"_id" : ObjectId("5abce315cabca22270eead6a"),
"typesOfExicution" : "validation",
"modesOfExicution" : "auto",
"automation[0][projectName]" : "Second",
"automation[0][modules][]" : "Second module",
"automation[0][assets][]" : "Second assets",
"companyName" : "VV"
}
/* 2 */
{
"_id" : ObjectId("5abce31ccabca22270eead6b"),
"typesOfExicution" : "validation",
"modesOfExicution" : "auto",
"automation[0][projectName]" : "Second",
"automation[0][modules][]" : "Second module",
"automation[0][assets][]" : "Second assets",
"companyName" : "VV"
}
/* 3 */
{
"_id" : ObjectId("5abce321cabca22270eead6c"),
"typesOfExicution" : "validation",
"modesOfExicution" : "auto",
"automation[0][projectName]" : "hdh",
"automation[0][modules][]" : "ds",
"automation[0][assets][]" : "djv",
"companyName" : "VV"
}
答案 0 :(得分:2)
这不是你应该如何在MongoDB中存储数组。您应该将数组元素存储为嵌入文档。正如@Alexis在这里提到的那样,对于你的数据库集合结构究竟是什么并不清楚,所以我希望这是根据你给定的输入预期的结果:
/* 1 */
{
"_id" : ObjectId("5abce315cabca22270eead6a"),
"typesOfExicution" : "validation",
"modesOfExicution" : "auto",
"automation" : [
{
"projectName" : "Second",
"modules" : [
"Second module"
],
"assets" : [
"Second assets"
]
}
],
"companyName" : "VV"
}
/* 2 */
{
"_id" : ObjectId("5abce31ccabca22270eead6b"),
"typesOfExicution" : "validation",
"modesOfExicution" : "auto",
"automation" : [
{
"projectName" : "Second",
"modules" : [
"Second module"
],
"assets" : [
"Second assets"
]
}
],
"companyName" : "VV"
}
/* 3 */
{
"_id" : ObjectId("5abce321cabca22270eead6c"),
"typesOfExicution" : "validation",
"modesOfExicution" : "auto",
"automation" : [
{
"projectName" : "hdh",
"modules" : [
"ds"
],
"assets" : [
"djv"
]
}
],
"companyName" : "VV"
}
按照上述说明获得数据后,请使用automation.projectName
,您应该得到如下结果:
答案 1 :(得分:1)
我不太确定您的存储文档的结构。我相信它看起来像:
{
"typesOfExicution": string,
"modesOfExicution": string,
"automation": [{ projectName: string, modules: string, assets: string }]
"companyName" : string
}
如果要对projectName
执行查询,该查询属于组成数组automation
的对象,则需要使用$elemMatch
运算符:
db.getCollection('SETTINGS').find({'companyName':'VV', 'typesOfExicution' : 'validation', 'automation' : { $elemMatch: { 'projectName': 'myProject' } } })