简体   繁体   中英

MongoDB - Embed document with _id into the child

I have a document that represents a store with your advertisements as follows:

{name: "name of store",
 address: "address of store",
 advertisements: [{title: "title of advertising", desc: "desc of advertising"}]
}

To increase read speed and insert or find an advertising from this store is easy but, to delete a specific advertising, how can I do this?

There is a way to add a _id field into the element inside advertisements array? This way, I could find a specific item by _id.

I don't like the approach that use $elemMatch to find an item by your name or other field that isn't de _id.

Thanks!

With embedded documents there are no _id fields, these are a property of the main document in the collection. There is a full explaination here: http://docs.mongodb.org/manual/core/document/

Any embedded documents or array elements or even documents within arrays are stored exactly as is, an in the natural form of how you would work with JSON structures or very close to most dynaminc language native representations.

In your case for documents within an array you can either use the $elemMatch query operator to find the document(s) you wish to remove.

{ name: "<matching name>", advertisements: { $elemMatch: { title: 'title of advertising'  } } }

Alternately there is the dot notation approach:

{ name: "<matching name>", advertisements.title = 'title of advertising' }

Or even index notation:

{ name: "<matching name>", advertisements[0] }

At any rate there are a collection of Array operators for use in updates so you can manipulate the elements.

Perhaps your real problem here is not with $elemMatch but with the structure of the documents contained having no unique key in which to access them. That being the case then maybe you should consider altering the structure of the sub-documents in your data to have a reasonable identifier for use in finding the documents you want. This is generally a best practice approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM