MongoDB finding all subdocuments where subDocument _ids like "string" -
sample document structure like:
{ "_id" : "https://docs.mongodb.org/manual", "collection" : { "_id" : "collection", "urls" : [ "https://docs.mongodb.org/manual/c1", "https://docs.mongodb.org/manual/c2" ] }, "collectionnew" : { "_id" : "collection1", "urls" : [ "https://docs.mongodb.org/manual/c1new", "https://docs.mongodb.org/manual/c2new" ] }, "log" : { "_id" : "log", "urls" : [ "https://docs.mongodb.org/manual/l1", "https://docs.mongodb.org/manual/l2" ] } }
i have multiple such documents in collection. after finding document
db.autosearch.find({"_id": "https://docs.mongodb.org/manual"})
i want search subdocuments under name "collection"
solution
i changed document structure to:
{ "_id" : "https://docs.mongodb.org/manual", "contents" : [ { "_id" : "connect", "urls" : [ "https://docs.mongodb.org/manual/search/?query=connect" ] }, { "_id" : "connection", "urls" : [ "https://docs.mongodb.org/manual/search/?query=connection", "https://docs.mongodb.org/manual/search/?query=connection%20pymongo" ] } { "_id" : "list", "urls" : [ "https://docs.mongodb.org/manual/search/?query=listfiles", "https://docs.mongodb.org/manual/search/?query=listdatabases", "https://docs.mongodb.org/manual/search/?query=listcommands" ] }, { "_id" : "log", "urls" : [ "http://docs.mongodb.org/manual/tutorial/rotate-log-files/", "http://docs.mongodb.org/manual/reference/log-messages/" ] }, { "_id" : "index", "urls" : [ "https://docs.mongodb.org/manual/search/?query=index-related%20commands" ] } ]}
then using mongodb aggregate query
db.autosearch.aggregate([{$match:{ "_id": "https://docs.mongodb.org/manual"}}, {$unwind: '$contents'}, {$match:{"contents._id":/connect/}}])
i got desired output.
Comments
Post a Comment