简体   繁体   中英

How Nested Find MongoDB ? Javascript

How to nested find in mongodb with collection data below :

{
 "_id": {
  "$oid": "585b998297f53460d5f760e6"
 },
 "newspaper": {
  "playerID": "57bffe76b6a70d6e2a3855b7",
  "playerUsername": "dennis",
  "player_newspaper": "{\"ID\":\"57bffe76b6a70d6e2a3855b7\",\"Username\":\"Dennis\",\"itemName\":\"Corn\",\"Comment\":\"Jagung Promo\",\"Date\":\"12/27/2016\"}"
 }
}

My code :

var datex = new Date();
var dates = datex.getMonth() + '/' + datex.getDate() + '/' + datex.getFullYear();
db.playerNewspaper.remove( {"newspaper.player_newspaper.Date": dates } } } ) ;

This is not working.

and

That's how I insert the data:

var currentPlayer = {
        "playerID": playerID,
        "playerUsername": playerUsername,
        "player_newspaper": newspaper

    }; // we construct a new player from the data we are about to input into the player data

    playerDataList.insert(
    {
      "newspaper" : currentPlayer
    } // Uses the $set mongo modifier to set old player data to the current player data
    );

Your query looks good but problem in your data. According to your query condition you assume that player_newspaper is an object but that data you shown there player_newspaper is a String . So in your query "newspaper.player_newspaper.Date": date not found any document that's why query not working.

Your document structure should be like:

{
    "_id" : ObjectId("585b998297f53460d5f760e6"),
    "newspaper" : {
        "playerID" : "57bffe76b6a70d6e2a3855b7",
        "playerUsername" : "dennis",
        "player_newspaper" : {
            "ID" : "57bffe76b6a70d6e2a3855b7",
            "Username" : "Dennis",
            "itemName" : "Corn",
            "Comment" : "Jagung Promo",
            "Date" : "12/27/2016"
        }
    }
}

Then your query will be working fine.

var datex = new Date();
var dates = datex.getMonth() + '/' + datex.getDate() + '/' + datex.getFullYear();
db.playerNewspaper.remove( {"newspaper.player_newspaper.Date": dates } } } ) ;

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