请考虑以下存储在stocks
集合中的mongo文档:
{
"_id" : ObjectId("5d14eb6e7a99c30956b842e1"),
"propertiesValues" : [
{
"property_id" : "5c5460604bb12b02277f26d5",
"value" : "SEMI FOSCO"
},
{
"property_id" : "5c38bb491cddf30213c2fb13",
"value" : "LL"
},
{
"property_id" : "5ba9304f13a60b02f1b5d2c1",
"value" : "GARGOYLE"
},
{
"property_id" : "5c38bbf01cddf30213c2fb17",
"value" : "7/8 pes"
},
{
"property_id" : "5c545ecd4bb12b02277f26ca",
"value" : "VESTUÁRIO"
}
],
"materialDefinition_id" : ObjectId("5b68b9d1a4e46302c325e01e"),
"deletedAt" : null,
"createdAt" : 1561652078846,
"__v" : 0
}
给定查询为什么不返回任何字段:
db.stocks.find({ propertiesValues: [ { property_id: '5ba9304f13a60b02f1b5d2c1', value: 'GARGOYLE' }, { property_id: '5c38bb491cddf30213c2fb13', value: 'LL' }, { property_id: '5c38bbf01cddf30213c2fb17', value: '7/8 pes' }, { property_id: '5c545ecd4bb12b02277f26ca', value: 'VESTUÁRIO' }, { property_id: '5c5460604bb12b02277f26d5', value: 'SEMI FOSCO' } ] },{}).pretty();
我原本希望通过给定的查询来检索给定的文档,但不会重新调整数据。
如何正确解决此问题(propertiesValue
可能以任何顺序发生,因此解决方案必须能够以存储它们的任何顺序返回确切的项目)
编辑
以下查询返回请求的数据:
db.stocks.find({ propertiesValues: [ { property_id: '5c5460604bb12b02277f26d5', value: 'SEMI FOSCO' }, { property_id: '5c38bb491cddf30213c2fb13', value: 'LL' }, { property_id: '5ba9304f13a60b02f1b5d2c1', value: 'GARGOYLE' }, { property_id: '5c38bbf01cddf30213c2fb17', value: '7/8 pes' }, { property_id: '5c545ecd4bb12b02277f26ca', value: 'VESTUÁRIO' }] },{}).pretty();
区别在于此查询是按文档的确切顺序进行的。
这对我不起作用,因为我不能保证查询参数的顺序,因此我需要一个符合以下条件的解决方案:
有效退货
propertiesValues
,请返回数据propertiesValues
的排列顺序不同,则返回数据无效的退货
propertiesValues
中有MORE或LESS元素,则不返回数据property_id
或value
)不同,则不返回数据换句话说,无论它们以什么顺序出现,我都需要property_id
和value
字段的精确匹配。
答案 0 :(得分:0)
首先,您在描述文档时指定的集合与要查询的集合是不同的。
向前移动,您可以使用$ all运算符进行查询。
db.collection.find({ propertiesValues: { "$all": [ { property_id: '5ba9304f13a60b02f1b5d2c1', value: 'GARGOYLE' }, { property_id: '5c38bb491cddf30213c2fb13', value: 'LL' }, { property_id: '5c38bbf01cddf30213c2fb17', value: '7/8 pes' }, { property_id: '5c545ecd4bb12b02277f26ca', value: 'VESTUÁRIO' }, { property_id: '5c5460604bb12b02277f26d5', value: 'SEMI FOSCO' } ] }}).pretty();
它将以任何顺序匹配文档。
MongoDB文档:https://docs.mongodb.com/manual/reference/operator/query/all/
答案 1 :(得分:0)
您应该像这样用$ all尝试它:
{ "propertiesValues": { "$size" : 5, "$all": [ { property_id: '5ba9304f13a60b02f1b5d2c1', value: 'GARGOYLE' }, { property_id: '5c38bb491cddf30213c2fb13', value: 'LL' }, { property_id: '5c38bbf01cddf30213c2fb17', value: '7/8 pes' }, { property_id: '5c545ecd4bb12b02277f26ca', value: 'VESTUÁRIO' }, { property_id: '5c5460604bb12b02277f26d5', value: 'SEMI FOSCO' } ] }}
添加$ size检查可以保证完全匹配。