使用 Doctrine 和 MongoDB 存储数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12941523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing array with Doctrine and MongoDB
提问by user1754256
How can I store an array with Doctrine and Mongo DB?
如何使用 Doctrine 和 Mongo DB 存储数组?
I do not want reference document, only array.
我不想要参考文件,只想要数组。
Example:
例子:
Type[
Type1,
Type2,
Type3
]
Do I need to create new Doctrine ODM data type?
我是否需要创建新的 Doctrine ODM 数据类型?
回答by jmikola
If you need to store values not mapped to a document class in an array, you can use the collectionfield mapping, which maps to a basic array in MongoDB. There is also a hashtype, which similarly converts an associative array in PHP to an object in MongoDB without mapping anything within it.
如果需要将未映射到文档类的值存储在数组中,可以使用collection字段映射,它映射到 MongoDB 中的基本数组。还有一种hash类型,它类似地将 PHP 中的关联数组转换为 MongoDB 中的对象,而不在其中映射任何内容。
If "Type" in your example is a mapped document class, then you'll want to use an EmbedManyrelationship, which will store one or more mapped documents in an array within the parent document. Within MongoDB, this will be represented as an array of objects, which is similar to what you could do yourself with the collectionfield (storing an array of associative arrays); however, ODM will utilize the EmbedMany mapping to hydrate those objects back to document instances.
如果示例中的“Type”是映射文档类,那么您将需要使用EmbedMany关系,它将一个或多个映射文档存储在父文档中的数组中。在 MongoDB 中,这将表示为一个对象数组,这类似于您自己可以对collection字段执行的操作(存储关联数组的数组);然而,ODM 将利用 EmbedMany 映射将这些对象水合回文档实例。
回答by Bhaktaraz
You can use mongo types hash or collection as your need.
您可以根据需要使用 mongo 类型的哈希或集合。
Hash :Stores and retrieves the value as associative array.
Hash :将值存储和检索为关联数组。
Collection :Stores and retrieves the value as numeric indexed array.
Collection :将值存储和检索为数字索引数组。
For example:
例如:
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
class Category
{
/**
* @MongoDB\Field(name="tags", type="collection")
*/
private $tags;
/**
* @MongoDB\Field(name="country_wise_total_count", type="hash")
*/
private $country_wise_total_count;
}
The data is stored such as :
数据存储如下:
"tags": [
"man",
"boy",
"male",
"sandal",
"cloth",
"army boots",
"boots",
"sport shoes",
"school",
"casual",
"office"
],
"country_wise_total_count": {
"NP": NumberInt(7),
"US" : NumberInt(10)
}
回答by Alfons Foubert
...
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
...
class MyClass
{
/**
* @MongoDB\Hash
*/
protected $tags = array();
}
Besides, you can check out BSPTagBundleif you want a form type that helps you with that type of variable.
此外,如果您想要一种可以帮助您处理该类型变量的表单类型,您可以查看BSPTagBundle。

