0

Good day to all. I want to delete all fields from document except a some list. I know about $unset operator, but I don't know how can I use it in my task. Thank you in advance.

Nesh
  • 1
  • 1
  • 1
    There is an answer here about listing all unique keys in a collection: http://stackoverflow.com/questions/2298870/mongodb-get-names-of-all-keys-in-collection then you could you could remove all keys you don't want to remove from that list. then loop through and unset the unneeded keys in each document. – AJ X. Nov 28 '16 at 17:13
  • I thought mongo has some operator(as $unset), which remove this fields by one request without loop. But I think this will help me. Thank you =) – Nesh Nov 29 '16 at 09:45

1 Answers1

0
db.products.update(
   { sku: "unknown" },
   { $unset: { quantity: "", instock: "" } }
)

The above query will delete quantity and instock fields from all the product documents where sku is unknown.

you can write your query on the lines of the above example, however if you simply want to remove few fields from every document just ignore the condition section i.e. sku :"unknown" instead pass {} and it will affect every document in your collection.

satish chennupati
  • 2,602
  • 1
  • 18
  • 27
  • Thank you, but I want to delete all fields except some list. I have only the list of fields which I want keep, and all other fields i want to delete. – Nesh Nov 29 '16 at 09:24
  • so you mean its the other way around. ok i wll try to figure out a query that helps you. – satish chennupati Nov 29 '16 at 12:31